Skip to content

Commit 9d2105b

Browse files
RayBBMichaReiser
andauthored
add instance variable examples to RUF012 (#15982)
## Summary Closes #15804 Add more examples to the documentation. Co-authored-by: Micha Reiser <micha@reiser.io>
1 parent 8fcac0f commit 9d2105b

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

crates/ruff_linter/src/rules/ruff/rules/mutable_class_default.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,20 @@ use crate::rules::ruff::rules::helpers::{
2424
/// `typing.ClassVar`. When mutability is not required, values should be
2525
/// immutable types, like `tuple` or `frozenset`.
2626
///
27+
/// For mutable variables, prefer to initialize them in `__init__`.
28+
///
2729
/// ## Examples
30+
///
31+
/// Using `ClassVar` and imutable types:
32+
///
2833
/// ```python
2934
/// class A:
3035
/// mutable_default: list[int] = []
3136
/// immutable_default: list[int] = []
3237
/// ```
3338
///
3439
/// Use instead:
40+
///
3541
/// ```python
3642
/// from typing import ClassVar
3743
///
@@ -40,6 +46,27 @@ use crate::rules::ruff::rules::helpers::{
4046
/// mutable_default: ClassVar[list[int]] = []
4147
/// immutable_default: tuple[int, ...] = ()
4248
/// ```
49+
///
50+
/// Using instance variables instead of class variables:
51+
///
52+
/// ```python
53+
/// class A:
54+
/// instance_dict: dict[str, str] = {"key": "value"}
55+
/// ```
56+
///
57+
/// Use instead:
58+
///
59+
/// ```python
60+
/// class A:
61+
/// instance_dict: ClassVar[dict[str, str]]
62+
///
63+
/// def __init__(self) -> None:
64+
/// self.instance_dict: dict[str, str] = {"key": "value"}
65+
/// ```
66+
///
67+
/// In cases where memory efficiency is a priority, `MappingProxyType`
68+
/// can be used to create immutable dictionaries that are shared between
69+
/// instances.
4370
#[derive(ViolationMetadata)]
4471
pub(crate) struct MutableClassDefault;
4572

0 commit comments

Comments
 (0)