conditional-ownership-mutation (MUT112)¶
Family: Mutation & State (MUT) · Heuristic · Opt-in · Experimental · Severity error (a bug) · No automatic fix
Opt-in: changing in place a value that is a new object on one path and borrowed state (a parameter, an attribute, a global, or what a function returns of such state) on another.
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.
Experimental
Its precision on real code bases is still low: much of what it reports is code that changes a borrowed container on purpose. 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¶
Checks for a container that is a new object on one path and borrowed state on another, and that
is then changed in place. The rule is opt-in: enable it with --extend-select MUT112 or
extend-select = ["MUT112"].
A value is a new object where the function makes it: a display ([], {}), a comprehension, a
copy (list(x), dict(x), x.copy(), copy.copy), a constructor call, an operator's result
(a + b), or a call of a project function that returns a new object. It is borrowed where it
comes from state that outlives the call: a parameter, an attribute, a global, a variable of an
enclosing function, an element of one of these, or a call of a project function that returns
such state. An attribute of an object the function makes itself (visitor = Visitor(), then
visitor.errors) is part of that object, not borrowed state. The paths meet in a conditional
expression or an if:
items = given or [],items = given if given else [];options = dict(defaults, **extra) if extra else defaults;seen = registry.get(key, {}),tags = getattr(obj, "tags", []);x = shared, thenif c: x = [].
What a project function returns is part of its summary, through any number of wrappers: a
function that returns its argument on one path and a new object on another makes its call's
result both when the caller passes borrowed state, also when that state is what another call
returns (identity(identity(shared))), and one returning an attribute it caches makes its
call's result borrowed. Only the returns a run can reach count: a return after a
while True: loop that no break leaves, or under if False:, returns nothing.
A change is an item assignment or deletion, a container method (append, extend, update,
setdefault, pop, ...), an in-place operator on a list, dict, set, or bytearray, or a
call of a project function that changes the container it is handed. The rule reports the first
change of the value in the function. It also reports:
- a change made by a closure to a variable of the enclosing function that holds such a value;
- a store of such a value in
self.<attr>when a method of the class, of a subclass, or of a base class changes that attribute in place (self.items.append(x), through an alias, or through a helper), at the store.
It does not report:
- a value that is a new object on every path, or borrowed on every path;
- a value rebound to a copy before the change (
x = list(x)), also when the copy is made only where the value is still the borrowed object (if x is shared: x = shared.copy()); - a value that a flag of the caller's copies, a test of parameters alone
(
if not in_place: x = x.copy(),list(x) if copy else x): where it does not copy, the function changes the borrowed object on purpose. A copy that another test picks (x if isinstance(x, set) else set(x),if config.get("strict"): x = set(x)) still counts; - the accumulator idiom, where a parameter is replaced by a new object only when it is
Noneor a sentinel (if out is None: out = [],out = [] if out is None else out): the function fills what its caller hands it. Such a value counts when it may also be a new object the test does not select (x = [] if fresh else outafter it), and when it is also stored onself, where the instance keeps the caller's object. A test that replaces nothing (if out is None: raise ...) leaves the parameter borrowed; - a new object the function stores in other state before the paths meet
(
rows = table[key] = [],table.setdefault(key, rows)): it is that state's on every path; - a value stored back where it borrows from, the same attribute of the same object or an item
of the same container (
self.items = self.items or [],d[k] = d.get(k) or [], but notself.items = other.items or []); - attributes named as memos or caches (
_cache,memo), which are meant to be filled; - removing from a value whose new objects all start empty (
d.get(k, {}).pop(x, None)): the removal does nothing to them; - a conditional expression changed in place without a name (
(a if c else b).append(x)): the code picks the container on purpose; - attribute assignments, and changes of a value below the borrowed one (
x[0].append(1)): a copy ofxshares those too (an item or attribute of a shallow copy ofx,dict(x)["k"], is the item ofxit holds, borrowed); selfin its own methods, and paths a branch on a constant never takes (while True:).
What a report states¶
A report states that a value that is a new object on one path and borrowed state (a parameter, an attribute, a global, or what a function returns of such state) on another is changed in place.
Its premises:
- New on one path: a display, comprehension, copy, constructor, operator, or a project function returning a new object. Established.
- Borrowed on another: the value comes from such state on another path. Established.
- Changed in place: directly, through a helper, or in a closure, after the paths meet. Open through a helper: a change on one of its paths is enough.
Why is this bad?¶
The function treats the value as its own on one path and changes a shared object on the other. The caller's list, a cached dictionary, or a class attribute changes only when the borrowed path runs, for example only when the caller passes a non-empty list, so the bug shows up far away and on some inputs only.
Example¶
def collect(name: str, scopes: list[str] | None = None) -> list[str]:
use_scopes = scopes or []
use_scopes.extend(lookup(name)) # MUT112: changes the caller's list when it is not empty
return use_scopes
Use instead:
def collect(name: str, scopes: list[str] | None = None) -> list[str]:
use_scopes = list(scopes or [])
use_scopes.extend(lookup(name))
return use_scopes
Known limitations¶
- The paths are not told apart by the tests on them: a value that an
if v is SENTINEL: returnexcludes, or a callee that returns its argument only when it is not a container, still counts, and so does a callee's borrowed return that a constant argument rules out (convert(data, ensure_copy=True)whereconvertreturnsdataitself only without it). - A new object that a function gets from a project call and stores on its argument before
returning it (
state = runtime.state = make_state()) still counts as new for its callers, which change the argument's state. - Calls of
async deffunctions and generators are not followed: their results are not what their bodies return. - A store in an attribute is followed for
selfonly.
Fix safety¶
No automatic fix.
Options¶
lint.extend-select = ["MUT112"]enables the rule.