Skip to content

Commit

Permalink
add instance variable examples to RUF012 (#15982)
Browse files Browse the repository at this point in the history
## Summary

Closes #15804 

Add more examples to the documentation.

Co-authored-by: Micha Reiser <[email protected]>
  • Loading branch information
RayBB and MichaReiser authored Feb 6, 2025
1 parent 8fcac0f commit 9d2105b
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions crates/ruff_linter/src/rules/ruff/rules/mutable_class_default.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,20 @@ 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] = []
/// immutable_default: list[int] = []
/// ```
///
/// Use instead:
///
/// ```python
/// from typing import ClassVar
///
Expand All @@ -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;

Expand Down

0 comments on commit 9d2105b

Please sign in to comment.