Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add instance variable examples to RUF012 #15982

Merged
merged 2 commits into from
Feb 6, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 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,7 +24,10 @@ 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] = []
Expand All @@ -40,6 +43,24 @@ 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
Loading