Skip to content

cached-property-stale-mutation (MUT101)

Family: Mutation & State (MUT) · Exact · Opt-in · Experimental · Severity error (a bug) · No automatic fix

Mutating an attribute read by @cached_property without invalidating the cache.

Experimental

Its precision outside a few code bases is still low. Experimental features can still change in behavior or precision, or be removed, in any release, and each change is listed in the release notes. An opt-in rule that is not experimental is stable and only off by default. See Experimental Features.

What it does

Opt-in: enable it with extend-select = ["MUT101"]. Its exact reports are true claims (census on the Stage 0-A corpus: 26 exact reports, none false; holdout: 1, none false), but few show real harm (1 of the 26 by majority of three reviewers), below the 10% share a default rule needs: most are writes that run before the property is first read, keep the value's meaning, or run on objects whose cached value nothing reads again.

Checks for methods that rebind or mutate an attribute that a @functools.cached_property of the same class (or of a subclass) reads, without invalidating the cached value. A method the class inherits from a project base class and does not override runs on its instances too, so it is checked against the class's cached properties (reported in the base class). A decorator is known by what its name is bound to in the module: an import alias counts (from functools import cached_property as cached), a decorator the module defines itself does not (a def cache(fn) of its own), and a name bound by neither counts by its spelling.

What a report states

An exact report states that whenever the method runs on an instance of any class that runs it, and that instance holds a value of the cached property when the write runs, the getter computed that value from the attribute the write rebinds or changes, and the instance still holds it when the method returns normally: the next read of the property returns a value computed from the attribute's state before the write. An instance that holds no value when the write runs makes the claim hold vacuously, whatever a later read keeps.

Its premises:

  • Cached property: every class the instance may be (R2, R5) that names the property gets it from a synchronous getter, the first definition along its MRO with no base heki does not know before it, decorated by a cached-property decorator the ecosystem catalog lists as keeping the value in the instance __dict__ ([[cached_properties]]: functools.cached_property and Django's, Werkzeug's, propcache's, and kombu's, R3; with Werkzeug's, which keeps it in a slot on an instance without a __dict__, no class along the MRO defines __slots__), and none has a metaclass other than type or abc.ABCMeta. An instance of a class that names nothing under the property's name holds no value of it, so the claim says nothing of it. Established.
  • Reads on every path: the getter reads the written attribute, with the written constant key or as a whole, on every path on which it returns normally, itself or through self methods and property reads it makes on every such path. Each of those runs its body at every call (no cache decorator) and has the fact. Established.
  • Every implementation: each of those calls has as its targets every implementation it can run (R2, R5). Established.
  • Plain write: the write is one of two kinds. It may rebind or delete the attribute with a plain store: no property, descriptor, __setattr__, __delattr__, or metaclass heki does not know in a class the instance may be, and every base a project class or a plain one. Or it may change in place the builtin list, dict, or set the attribute holds by its type, through a changing method or an item store that no project subclass of the container replaces. Established.
  • Kept to the return: no point from the write to the method's normal return may remove or replace the kept value, exception edges into handlers included. The write's own instruction counts: an in-place change runs code while it changes the attribute (it iterates its argument or hashes a key). That rules out a store or a deletion of the property's name, or of an item of a __dict__ under it, through any reference (self, a parameter, a closure, a global, an item of a container, *args, setattr, vars()), except one heki establishes as an object that keeps no value under the name: a value the method builds, or an instance of classes none of which (R2) binds a property getter of that name. A store or a deletion of a __dict__ or a __class__, an await (also the implicit ones of async for and async with), and a yield count as removing every value. It also rules out every call except two kinds: a project call whose targets are every implementation it can run and remove nothing, and a call of a library the catalog covers that runs no project code by its [[invokes]] entry, or, without one, is handed no callable, no instance of a project class, and no value of unknown type (R3). Implicit calls count the same. A special method an instruction runs on an operand's class (an operator, a comparison, in, a conversion or format, a subscript and its key, an unpacking, a call's * and ** arguments, a key a set or dict display hashes, a truth test, with) runs no code of the project only where heki establishes what implements it on every class the operand may be (R2): object's; a builtin type's, with what it runs on the items it holds (a container's comparison, hash, or repr() runs its items', and a dict or set compares a key with each key it holds under an equal hash, the names of attributes, strings, in an object's __dict__); or a library class's, as a call of that library (R3). A value of a nominal container ABC (Sequence, Mapping, collections.abc.Set, and their mutable ABCs, which accept only the classes deriving from them or registered with them) is one of its family's builtins or of another class outside the project, taken to run what they run, or of a project class implementing it: one deriving, through project classes, from the ABC or from a class of its family (list, tuple, dict, OrderedDict, UserDict, ChainMap, ...), or one registered with them (Mapping.register(C), @Mapping.register), and the method it runs is established as on those classes (a method of the ABC as the builtin's, unless such a class binds it or inherits it from a class outside the project). A register heki cannot resolve, or a __subclasshook__ of such a class (which may accept any class), leaves the family's values established by none. A value of any other abstract class (Iterable, Collection) or of a protocol, one annotated object, and one of a class heki does not know establish none, and a comparison's or a conversion's result is a builtin bool or str only where those methods are object's or a builtin type's. No attribute access may run a __getattr__, __setattr__, property, or other descriptor of the project that heki does not resolve (an access on a library object counts as a call of that attribute), no raise may construct a value that may be a class of the project, and no class statement or import of a project module runs there. Established.

Besides R1-R7, the claim assumes that no finalizer (__del__, which reference counting or the garbage collector runs when it frees an object) and no other thread runs code between the write and the method's return: either may remove the value at any instruction, and no premise rules them out.

Not part of the claim: whether the method runs after the property was first read. A write that runs only during two-phase setup makes the claim hold vacuously, so a setup step stays heuristic (After setup is open): a finalizer (__del__), a method that an __init__ along the MRO of a class the instance may be calls on the instance or stores through (a property setter), and lazy setup through a second cached property (the writer is a listed cached-property getter that no function of the project invalidates by name, and the property's getter reads it on every path).

A heuristic report states that a method that can run after initialization rebinds or changes an attribute that a @cached_property of the class family reads, and that a path after the write leaves the cached value in place. Open: the property may read the attribute on some paths only (through a call, one path of the callee is enough), initialization hooks are recognized by their names, a cached_property of a library the catalog does not list counts by its name, and calls after the write may remove the value.

Why is this bad?

A cached_property computes its value once and stores it in the instance __dict__. Once the attribute it was computed from changes, the property keeps returning the old value until the cache entry is deleted. The stale value is usually noticed far away from the write.

The rule follows self.helper() calls in both directions (a property that reads through a helper, a method that writes through a helper) and the getters of the properties the cached property reads (self.key where the @property key reads self.name), and reports the write itself, once per property. A property that also defines a setter or deleter is not followed. It does not report:

  • two-phase initialization: __init__, __post_init__, model_post_init, __setstate__, __enter__, setup, setup_* / _setup_* / _init_* / _configure_* methods, and private helpers called from __init__;
  • classes with a metaclass other than type / abc.ABCMeta along their MRO (also one heki cannot resolve): the metaclass may turn attribute writes into descriptor calls (a generated property whose setter invalidates the cached value), which heki does not see;
  • memo / cache dictionaries (self._cache[key] = value, setdefault, the if key not in self._memo: pattern): in-place changes of an attribute with a cache or memo word in its name; rebinding it (self.cache_size = n) and names such as memory_limit are no memo operation;
  • constant dictionary keys the property never reads (self.params["proxy"] while the property reads self.params["outtmpl"]);
  • writes after which every path invalidates the property (del self.prop, self.__dict__.pop("prop", None) or vars(self).pop("prop", None), also with the key in a string constant as MUT201 follows it, a self method that does), or before which every path already did and nothing read it since; an invalidation under a condition, such as if clear:, leaves the other path stale and is reported;
  • private helpers whose every caller invalidates the property;
  • lazy initialization: a write where a None / falsy test of the attribute found it unset (if self._conn is None: self._conn = connect(), also in a @property getter; the test may be of getattr(self, "_conn", None) or hasattr(self, "_conn"), or the write in the except AttributeError: clause of a try that reads it), when the cached property reads the attribute only through such initializations (return self._connect().db): computing the cached value set the attribute, so the test cannot find it unset again. A cached property that reads it directly (return self._conn is not None) may have cached its unset value and is reported;
  • changes made in place (clear(), append(), item assignment) to an attribute whose object the cached value holds itself, when the getter reads it for nothing else: it returns self.items, or puts it as itself into a display or a container it returns ({"items": self.items}, ctx["k"] = (x, self.items)). The cached value sees those changes; rebinding the attribute (self.items = []) is still reported. A getter that also computes from it (len(self.items)), copies it (list(self.items), (*self.items,)), reads it through a self method or property, or hands self to other code is reported as before. A self call whose result the getter discards (self.finalize() before return self.items) counts only when it writes an attribute the getter reads, itself or through a call whose result it uses.

Example

from functools import cached_property


class Settings:
    def __init__(self, raw: dict[str, str]) -> None:
        self.raw = raw

    @cached_property
    def keys(self) -> tuple[str, ...]:
        return tuple(self.raw)

    def replace(self, raw: dict[str, str]) -> None:
        self.raw = raw  # `self.keys` still returns the old keys

Use instead:

    def replace(self, raw: dict[str, str]) -> None:
        self.raw = raw
        self.__dict__.pop("keys", None)  # or `del self.keys` when it was computed

Fix safety

No automatic fix: whether to invalidate, recompute, or make the attribute read-only is a design decision.