Skip to content

change-lost-on-new-object (MUT119)

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

An in-place change of a builtin container applied to a new object that nothing else holds and no name keeps (list(xs).sort(), env = os.environ.copy().update(...), obj.settings[k] = v with a getter returning a new dict): the change is lost when the statement ends.

What it does

Checks in-place changes of a builtin container (list, dict, set, bytearray, collections.deque) applied to a new object that nothing else holds and that the code never names: list(xs).sort(), env = os.environ.copy().update(HOME=home), task.environment["KEY"] = value when the environment getter returns a new dict. Nothing can read the object after the statement, so the change is lost.

The object is the value of the expression the change is applied to, and it is new when it is:

  • built as the builtin itself: a display, a comprehension, a call of list, dict, set, bytearray, collections.deque, or sorted;
  • a copy the ecosystem catalog describes (x.copy() of a builtin container, copy.copy(x), os.environ.copy()) of a value whose builtin container type heki knows, called with nothing but the value it copies (copy.deepcopy(x, memo) keeps the copy in memo), or a slice of a list or bytearray;
  • what a call of a project function, or a read of a property, returns, when every return of each function the call can run is such an object and the function keeps it nowhere: not stored, captured, yielded, raised, handed to a call that may keep it (a builtin that only inspects its argument, such as len, keeps nothing), handed to a method whose result may hold it (a view such as d.values() or an iterator holds it, unless only a loop or a test reads it), used as a key (del registry[items] hands it to the registry's __delitem__), or read through an attribute (a bound method holds its object). A function returning the result of another such function qualifies too.

The change is a changing method of the object's own type (append, extend, insert, sort, reverse, update, pop, clear, setdefault, add, discard, remove, ...), an item assignment, an augmented item assignment (d()[k] += 1), or an item deletion. A method returning None is reported when its result is unused, or bound to a name or stored (opts[k] = list(v).extend(w)); pop, popitem, popleft, and setdefault only when their result is unused.

It does not report:

  • a method of a project class, even one named like a container's (Inventory.remove returning a filtered copy);
  • an object bound to a name first (items = list(xs), then items.sort()): whether a later statement reads it is a question of flow;
  • a result the code reads (top = list(heap).pop(), return list(xs).sort() or xs);
  • what a function returns when it may return state that outlives the call, keeps the new object somewhere, returns None on some path, is a generator or async def, or is decorated with a cache (functools.cache, cached_property): the change is then seen elsewhere.

A test that changes a returned copy on purpose to check that it is a copy is reported; suppress it there.

Type checkers report one of these shapes: mypy reports a None result stored into an item or an attribute (opts[k] = list(v).extend(w)) as func-returns-value, in the functions it checks, but not one bound to a name, and none of the other shapes; pyright and ty report none of them.

What a report states

A report states that the object the change is applied to is new, that nothing else holds it and no name keeps it, and that the change is one its builtin type makes in place, so the change is lost when the statement ends.

Its premises:

  • New object: the object is built as the builtin itself where it is changed, copied there by a copy the catalog describes from a value of a builtin container type no project subclass copies otherwise (R2), or returned by project functions whose every return is such an object that they keep nowhere, and the call or property read, and each one whose result those functions return, resolves to every function it can run. Open for a copy whose class only comes from the copied value's type (R2) when a project subclass may replace the copy or the change, for the result of a function returning such a copy, and when the call may run functions heki does not resolve.
  • Unnamed: the object is only the value of the changed expression; nothing reads it but the change and, for an augmented item assignment, the item load it starts with.
  • Changed in place: the change is a changing method of the object's builtin type, an item assignment, or an item deletion, and its result is unused or a None bound to a name or stored. Open for an augmented item assignment, whose item's own in-place operator runs first and may change an item other code holds.

Why is this bad?

The statement reads like an update, but it changes an object that disappears when the statement ends: the sort, the override, or the new item never reaches the code that reads the value. A None bound or stored in its place (environ = os.environ.copy().update(...)) fails later and far from the cause.

Example

import os


class Task:
    @property
    def environment(self):
        return {}

    def run(self):
        self.environment["PYTHONPATH"] = "/app"  # the dict is gone after this line


def child_env(home):
    env = os.environ.copy().update(HOME=home)  # `env` is None
    return env

Use instead:

import os


class Task:
    def __init__(self):
        self.environment = {}

    def run(self):
        self.environment["PYTHONPATH"] = "/app"


def child_env(home):
    env = os.environ.copy()
    env.update(HOME=home)
    return env

Known limitations

  • A comprehension changed in the same expression ([x for x in xs].append(y)) is not reported: its own appends read the new list too.
  • A new object bound to a name and never read again is out of scope.
  • Library functions returning new containers (str.split, json.loads) are not followed unless the catalog describes them as copies.
  • A function that compares the new object (items == other, items in seen) or tests it with isinstance is taken to keep nothing: a project __eq__, __contains__, or metaclass __instancecheck__ that stored the operand it is handed would keep it. These hooks answer a test, and code that stores their operand is not known.