Skip to content

cached-result-mutation (MUT114)

Family: Mutation & State (MUT) · Exact · Enabled by default · Severity error (a bug) · No automatic fix

Changing in place the list, dict, or set that a functools.lru_cache / functools.cache function returned (the cache hands the same object to later calls with the same arguments), directly or through the functions that return it.

What it does

Checks in-place changes of an object that a function cached by functools.lru_cache / functools.cache returned. The cache hands the same object to every later call with the same arguments, so the change is seen by all of them.

A report is exact when the function changes in place, at the reported line, the list, dict, or set that a cached function returned:

  • the cached function is decorated with functools.cache, or with functools.lru_cache whose maxsize is left out, None, or a literal number above 0 (a name holding 0 would keep nothing), known by what its name is bound to (from functools import lru_cache as _lru_cache counts, a cache decorator the module defines itself does not), and otherwise only with staticmethod, classmethod, typing.override, or typing.final (also of typing_extensions);
  • it takes a parameter besides a method's self / cls, so the cache keys its results;
  • every return a run can reach hands out a builtin container of one kind: its return annotation names list, dict, or set as a whole (dict[str, Any], not dict | None), or each returned value is built as one (a display, a comprehension, list(...), dict(...), set(...), sorted(...), str.split(...));
  • the changed object is the result of a direct call of that one function on every path to the line, through assignments, with no copy;
  • the line is an in-place change of a container of that kind: an item store or delete on a list or dict, a method that changes it (append, update, pop, add, ...), or an augmented assignment that changes it in place (+= on a list, |= on a dict or set), and no project subclass of that container overrides the method or operator.

The other changes of a cached function's result are heuristic reports: an object below the result (cached(k)["rows"].append(x)), an instance of a class, a value handed out through other functions that return it on some path, a change made by a helper the value is passed to, and a function that returns its cached value on some paths only.

Mutations through attributes, subscripts, container methods, in-place operators, and helpers that mutate their argument are followed for the heuristic reports, with the same copies and memo fills as MUT202 (readonly-return-mutation).

What a report states

An exact report states that the function changes in place, at the reported line, the list, dict, or set that a function cached by functools.lru_cache / functools.cache returned.

Its premises:

  • Cached: the decorator is functools.cache, or functools.lru_cache with maxsize left out, None, or a literal number above 0, known by what its name is bound to. Established.
  • Keyed: the cached function takes a parameter besides self / cls. Established.
  • Container kind: every return a run can reach hands out a builtin container of the named kind, by its return annotation (R2) or by construction. Established.
  • Same object: the changed object is that call's result on every path, with no copy, and the call runs that function: the project binds no name the call goes through to another object (assumption R1, as for EFF101). Established.
  • Changed in place: the line is an in-place change of a container of that kind. When only the return annotation names the kind, no project subclass of that container overrides the method or operator, has a metaclass that may install it, or, for a method called by name, defines __getattribute__ (under R2 the result may be an instance of one, whose sort or __ior__ may change nothing). Established.

A heuristic report states that the function changes an object that a cached function returned, or an object below it. Open: the value may be the cached one on some paths only, and the object may be a class instance whose change heki cannot tell from a memo fill.

Why is this bad?

A cached return value is shared by every caller with the same arguments. Changing it in place corrupts the cache for every later caller, usually long after the change happened.

Example

from functools import lru_cache


@lru_cache(maxsize=32)
def fields(name: str) -> list[str]:
    return [name, "id"]


def extended(name: str) -> list[str]:
    result = fields(name)
    result.append("extra")  # changes the list the cache keeps
    return result

Use instead:

def extended(name: str) -> list[str]:
    result = list(fields(name))
    result.append("extra")
    return result

Known limitations

  • A cached value stored in an attribute (self.kept = fields(...)) and changed in another method is not followed.
  • A generator's values and a coroutine's result (await) are not followed.

Fix safety

No automatic fix.