readonly-param-mutation (MUT110)¶
Family: Mutation & State (MUT) · Exact · Enabled by default · Severity warning (a bug that is rarely harmful) · No automatic fix
Handing a Sequence / Mapping / AbstractSet / ReadOnly parameter, as itself, to a function whose body (or a helper's) changes it in place at a named line.
What it does¶
Checks functions that hand a parameter annotated as a read-only container to code that changes
it in place: a parameter annotated Sequence[...], Mapping[...], AbstractSet[...]
(typing.AbstractSet or collections.abc.Set, not typing.Set, which is set), or
ReadOnly[...] (also inside Optional, | None, Annotated, and quotes), passed as itself,
through a local alias (alias = items), or through a call that hands it back as itself
(typing.cast(list[int], items), a project function returning its parameter on every path) to
a function that changes its argument in place
(items.sort(), items.append(...), table[key] = ..., tags.add(...)), itself or through
further helpers, any number of calls deep.
The rule reports the call that hands the parameter over, and names the line where the change
happens, with the calls down to it and the line itself as related locations. A generator function changes what it is handed where its generator is
iterated (for, list(...), a function iterating it), and is reported there; one that is
created and never iterated changes nothing.
It does not report:
- a change in the function itself (
items.append(1),alias = items; alias.append(1)): type checkers report it on the read-only type. A change through a value a call hands back as itself is reported, at the change:cast(list, items).append(1)andsame(items).append(1)hide the read-only type from the type checker; - a container inside the argument (
values["a"].append(1)withvalues: Mapping[str, list[int]]): only the argument itself counts; - a call that hands over a copy (
helper(list(items)),helper(dict(table)),helper(set(tags))); - a helper parameter annotated with a mutable type (
list[int],dict[str, int],set[int],MutableSequence[int],deque[int], ...): the type checker reports the argument, unless a call handed it back (fill(cast(list[int], items))), which the type checker accepts; - a helper parameter annotated read-only: that helper is checked in turn (its own handing over is reported, a change in its own body is a type error); a change reached only through such a helper, or through one whose parameter is annotated with a mutable type, further down the calls, is no report of the outer call either;
- variadic parameters (
*items: Sequence[int]).
What a report states¶
A report states that the function hands its parameter annotated Sequence, Mapping,
AbstractSet, or ReadOnly, as itself, to a function, and that whenever the named line runs
during that call, it changes the caller's object in place. A report at a change in the function
itself states that the line changes the object bound to the parameter in place, through a value a
call handed back as itself. It does not say that every call
reaches the line: the change often sits under a test of the argument's type
(if isinstance(values, list):), and the claim is anchored there.
Its premises:
- Read-only parameter: the parameter's annotation. Established.
- Passed as itself: on every path to the call (or to the change in the function itself),
the value is the parameter, a local alias of it, or what a call hands back of it as itself:
typing.cast, or a call binding only project functions that return that parameter on every path. Not a copy or another value. Established. A function returning another call's result (return same(x)) is open, and its call hands nothing back. - Changed at the line: the named line changes in place the object bound to the parameter of
the function it is in, on every path to the line, a builtin container there (
list,dict,set,bytearray,deque, ... by annotation, construction, or anisinstancetest), and that parameter receives the argument through the calls shown, each handing it on as itself, none of them annotated. No project subclass of that container overrides the changing method (reverse,__setitem__,__iadd__, ...), has a metaclass that may install it, or, for a method called by name, defines__getattribute__: under R2 the value may be an instance of one. Established. Open: a change of a value of another class (aSequencewhoseappendreturns a new one), a change by a method a project subclass overrides, and one made where a generator that another function returns is iterated; such a report names no line and is heuristic.
Why is this bad?¶
A Sequence, Mapping, or AbstractSet annotation promises the caller that the function only
reads its argument, so callers pass their own lists, dictionaries, and sets, shared values, or
tuples and frozensets. A helper that changes the argument in place breaks the promise: the
caller's object changes behind its back, or the call fails on a tuple or a frozenset. Type
checkers trust the helper's signature, so an unannotated or Any helper accepts the Sequence
and hides the change.
Example¶
from collections.abc import Sequence
def sort_values(values):
values.sort()
def median(values: Sequence[float]) -> float:
sort_values(values) # MUT110: reorders the caller's list
return values[len(values) // 2]
Use instead:
from collections.abc import Sequence
def median(values: Sequence[float]) -> float:
ordered = sorted(values)
return ordered[len(ordered) // 2]
If the helper is meant to change its argument, annotate its parameter with a mutable type
(def sort_values(values: list[float]) -> None): the type checker then shows the mismatch at
the call.
Fix safety¶
No automatic fix.
Options¶
No configuration: the rule reads standard typing declarations only.