shallow-copy-nested-mutation (MUT115)¶
Family: Mutation & State (MUT) · Heuristic · Opt-in · Severity error (a bug) · No automatic fix
Opt-in: changing in place an object below a shallow copy the function made of state that outlives the call (dict(x), x.copy(), copy.copy(x), model_copy()): the copied value holds the same object, so the change is seen through it too.
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 an object that the function reaches below a shallow copy it made
itself of state that outlives the call: a parameter, a global, a variable of an enclosing
function, or an attribute or item read from such state. A shallow copy is a new object holding the same objects as the copied
value, so changing one of those objects changes it for the copied value too.
The rule is opt-in: enable it with --extend-select MUT115 or extend-select = ["MUT115"].
The copies are those MUT202 follows: a builtin container's copy(), dict(x), list(x),
set(x), a display that only unpacks the value ({**x}, [*x]), a slice of a builtin list,
copy.copy, copy.replace, dataclasses.replace, a pydantic model's model_copy() without
deep=True, and the shallow copy sanitizers of the ecosystem catalog. The change is an item
store or delete, a changing method (append, update, pop, ...), an in-place operator, or an
attribute store or delete, on an object read from the copy (copied["tags"],
copied.children, copied.data_type.type = "int"), directly or through a helper the object is
handed to.
It does not report:
- a change of the copy itself (
copied["k"] = v,copied.name = v): the copy is the function's own; - an object the copy was given a value of its own for: rebound before the change on every path
(
copied.tags = [*tags], thencopied.tags.append(x)), passed toreplace(x, tags=...), or named bymodel_copy(update={"tags": ...}); - a deep copy (
copy.deepcopy,model_copy(deep=True)); - a store into the copy's own
__dict__(copied.__dict__["_k"] = v); - the elements of an iteration over the copy (
for task in list(tasks): task.x = 1): iterating a copy is how code changes a container while looping over it; - a copy of a value the function made itself;
- filling a memo of the shared object, or initializing one of its attributes lazily (as for
MUT202).
What a report states¶
A report states that the function changes in place, at the reported line, an object that it reaches below a shallow copy it made of a value it did not make (a parameter, a global, a variable of an enclosing function, or an attribute or item read from one), and that the copied value held that object at that place when the function copied it.
Its premises:
- Shallow copy: the value is the result of a copy that shares what is below its top level: a
builtin container's
copy(), its constructor (dict(x),list(x),set(x)),{**x},[*x], or a slice, of a builtin container (by annotation, R2) whose copying methods no project subclass replaces;copy.copyof an instance of a project class no class of which (R2) defines__copy__,__reduce__,__reduce_ex__,__getstate__, or__setstate__, or has a metaclass or a base heki does not know; ormodel_copy()withoutdeep=Trueof a pydantic model (R3) whose classes define no__copy__ormodel_copy. Open for the other copies (dataclasses.replace,copy.replace, the catalog's other sanitizers). - Borrowed original: on every path the copied value is state that outlives the call: a parameter, a global, a variable of an enclosing function, or what a plain attribute or item load reads from such state. Open: one path is enough. What a call returns is not followed.
- Still shared: on every path to the line, the changed object is what the copy holds at one
of its levels, read from the copy by a plain item or attribute load (an item of a builtin list
or dict, a plain attribute of an instance), and nothing gives that level a value of its own:
no store or delete of it into the copy, no keyword of the copy call or
update=key naming it, no method changing a copied container's items, and the copy reaches no other code. Open: a value that is below the copy on one path counts, and so does an object further below (copied["a"]["b"]): it lives in an object the copied value shares, which any code reaching that object may have given a new one since the copy. - Changed below the copy: the line changes that object in place: an item store or delete, a
changing method, or an in-place operator on a builtin
list,dict, orset(by annotation, R2) that no project subclass replaces, or a plain attribute store or delete on an instance of a project class (no property, descriptor,__setattr__, or metaclass in a class it may be; pydantic'sBaseModel.__setattr__stores on the instance, R3). Open: a change made by a helper the object is handed to.
Why is this bad?¶
The copy suggests the original stays as it was, but the objects below the copy are the original's. Changing one through the copy changes the original, usually far from where the copy was made: a default shared by every model, an option dictionary of the caller, a node of a tree another part of the program still reads.
Example¶
def with_base(options: dict[str, list[str]], base: str) -> dict[str, list[str]]:
result = options.copy()
result["bases"].append(base) # changes the list `options["bases"]` holds
return result
Use instead:
def with_base(options: dict[str, list[str]], base: str) -> dict[str, list[str]]:
result = options.copy()
result["bases"] = [*result["bases"], base]
return result
Known limitations¶
- A copy made by a project function (
copy_deep()that copies one level and shares the next) is not followed: a project copy method copies as deeply as its body does, which its summary does not state level by level. - A copy stored in an attribute and changed in another method is not followed.
Fix safety¶
No automatic fix.