Skip to content

mutable-class-default (RUF012)#

What it does#

Checks for mutable default values in class attributes.

Why is this bad?#

Mutable default values share state across all instances of the class, while not being obvious. This can lead to bugs when the attributes are changed in one instance, as those changes will unexpectedly affect all other instances.

When mutable values are intended, they should be annotated with typing.ClassVar. When mutability is not required, values should be immutable types, like tuple or frozenset.

Examples#

class A:
    mutable_default: list[int] = []
    immutable_default: list[int] = []

Use instead:

from typing import ClassVar


class A:
    mutable_default: ClassVar[list[int]] = []
    immutable_default: tuple[int, ...] = ()