add instance variable examples to RUF012 (#15982)

## Summary

Closes #15804 

Add more examples to the documentation.

Co-authored-by: Micha Reiser <micha@reiser.io>
This commit is contained in:
Raymond Berger 2025-02-06 09:01:09 -05:00 committed by GitHub
parent 8fcac0ff36
commit 9d2105b863
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 27 additions and 0 deletions

View File

@ -24,7 +24,12 @@ use crate::rules::ruff::rules::helpers::{
/// `typing.ClassVar`. When mutability is not required, values should be
/// immutable types, like `tuple` or `frozenset`.
///
/// For mutable variables, prefer to initialize them in `__init__`.
///
/// ## Examples
///
/// Using `ClassVar` and imutable types:
///
/// ```python
/// class A:
/// mutable_default: list[int] = []
@ -32,6 +37,7 @@ use crate::rules::ruff::rules::helpers::{
/// ```
///
/// Use instead:
///
/// ```python
/// from typing import ClassVar
///
@ -40,6 +46,27 @@ use crate::rules::ruff::rules::helpers::{
/// mutable_default: ClassVar[list[int]] = []
/// immutable_default: tuple[int, ...] = ()
/// ```
///
/// Using instance variables instead of class variables:
///
/// ```python
/// class A:
/// instance_dict: dict[str, str] = {"key": "value"}
/// ```
///
/// Use instead:
///
/// ```python
/// class A:
/// instance_dict: ClassVar[dict[str, str]]
///
/// def __init__(self) -> None:
/// self.instance_dict: dict[str, str] = {"key": "value"}
/// ```
///
/// In cases where memory efficiency is a priority, `MappingProxyType`
/// can be used to create immutable dictionaries that are shared between
/// instances.
#[derive(ViolationMetadata)]
pub(crate) struct MutableClassDefault;