readonly-type-mutation (MUT108)¶
Family: Mutation & State (MUT) · Heuristic · Opt-in · Severity error (a bug) · No automatic fix
Opt-in: changing in place a field that a standard type declares read-only (frozen dataclass / NamedTuple / dataclass_transform fields, Final / ReadOnly attributes, ReadOnly TypedDict keys), directly, through an alias, or in a helper.
Heuristic
This rule is heuristic: a premise of its claim can be open ("What a report states" lists them), so a report can be wrong about the code. It runs only when select or extend-select names its code or name. It has not been measured yet. See Rule Precision.
What it does¶
Checks in-place changes of containers held in fields that a standard type declares read-only, which type checkers let through because they only stop rebinding:
- a field that holds a container in a
@dataclass(frozen=True), aNamedTuple, or a class that a PEP 681dataclass_transform(frozen_default=True)builds (a decorator function, base class, or metaclass carrying it, unless the class passesfrozen=False), also on an instance of a subclass:config.tags.append(...); - an attribute declared
Final[...](self.items: Final[list[int]] = []in__init__, or aFinalfield of a dataclass orNamedTuple) orReadOnly[...], and aReadOnlykey of aTypedDict(movie["names"].append(...)).
A Sequence / Mapping / AbstractSet parameter handed to a helper that changes it is
MUT110 (readonly-param-mutation), which shares this analysis.
Changes are followed through local aliases (tags = config.tags; tags.append(...)) and through
helpers, annotated or not and any number of calls deep, that change what they are handed: the
attribute itself (add_default(config.tags)) or the object holding it (reset(config)). Such a
change is reported at the call that hands the attribute or the object over, with the calls down
to the change as related locations. A helper that sees the object's type reports its own change
instead. A generator function changes what it is handed where its generator is iterated, and is
reported there; one that is created and never iterated changes nothing.
The rule does not report:
- rebinding or deleting the attribute (
config.tags = [],del config.tags): type checkers report it; object.__setattr__(...),setattr(...), and__dict__writes: the deliberate way to set up a frozen instance, caches included;- the class's own initialization:
__init__,__post_init__,__new__,model_post_init,__setstate__changing their own instance, also through helpers that only run inside them; - an instance the function constructs itself and fills before anyone else holds it
(
index = Index({}, {}); index.names["a"] = 1), directly or through a helper; - fields declared
field(compare=False)(state outside the instance's value, such as a cache); fields and attributes whose annotation is no container type (an object of a project class changes through its own methods); class variables (ClassVar); class-level constants of other classes; and module-level constants; - a container inside the read-only one (
config.tables["a"].append(1)with a frozentables: dict[str, list[int]]): only the container in the read-only field counts.
Out of scope: dataclass_transforms defined outside the checked files, such as the frozen models
of attrs and Pydantic (heki does not analyze installed packages, so it cannot see the
transform); properties with a setter; TypedDict values read through .get()
(movie.get("names")); and objects whose class heki cannot see (an Any or unannotated
receiver).
What a report states¶
A report states that the code changes in place a container held in a field that a standard type declares read-only, directly, through an alias, or through the helpers shown.
Its premises:
- Read-only field: the class declares the field read-only (frozen dataclass,
NamedTuple,dataclass_transform,Final,ReadOnly). Established from the declarations. - Instance: the object is an instance of the class or of a subclass, by construction or annotation (assumption R2).
- Changed in place: an item store, a mutator method, or a helper changing its argument. Open through a helper: a change on one of its paths is enough.
Why is this bad?¶
A frozen dataclass or a NamedTuple promises immutable instances, so code shares them freely: as
module-level defaults, in caches, or by handing the same value to several owners. An in-place
change of a container inside one is seen by every holder and changes the results of ==. A
Final or ReadOnly declaration makes the same promise to the readers of the value. Type
checkers stop the rebinding, but not a change of the container inside, directly, through an
alias, or in a helper that receives a plain list or an unannotated value.
Example¶
from dataclasses import dataclass, field
def add_default(tags):
tags.append("default")
@dataclass(frozen=True)
class Config:
tags: list[str] = field(default_factory=list)
def configure(config: Config) -> None:
add_default(config.tags) # MUT108: changes the frozen `Config.tags` in place
Use instead:
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Config:
tags: tuple[str, ...] = ()
def configure(config: Config) -> Config:
return replace(config, tags=(*config.tags, "default"))
Fix safety¶
No automatic fix.
Options¶
lint.extend-select = ["MUT108"](or--extend-select MUT108) enables the rule. It is opt-in: selecting theMUTprefix does not enable it.- No other configuration: the rule reads standard
typinganddataclassesdeclarations only.