Skip to content

iterated-container-mutation (MUT113)

Family: Mutation & State (MUT) · Heuristic · Opt-in · Experimental · Severity error (a bug) · No automatic fix

Opt-in: a dict, set, or deque of the instance changed while a method iterates it, by another method while a generator is suspended in the loop or by a function the loop's body calls (the next step raises RuntimeError).

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

It has few reports, and most of them are still false. 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 dict, set, or collections.deque held in an attribute of self that is changed in place while a method of the class iterates it, by code outside the loop:

  • a method of the class that runs while a generator method is suspended inside the iteration (at a yield from which the loop goes on, or inside a yield from);
  • a function or method that the loop's body calls.

The rule is opt-in: enable it with --extend-select MUT113 or extend-select = ["MUT113"].

An iteration is a for loop or a yield from over the container, over its keys(), values(), or items() view, or over a lazy wrapper of either (iter, enumerate, zip, map, filter, reversed, itertools.chain, a generator expression, ...). A snapshot (list(...), tuple(...), sorted(...), .copy()) is a container of its own. The container's class comes from its annotation or its assignment in __init__ (OrderedDict, defaultdict, and Counter are mappings).

A change is an in-place change of the attribute's container, made by the method itself, by the methods and properties it calls on self, or by a helper it hands the container to (the helper's change counts as the same change made in the method):

  • inserting, removing, or moving items: append, add, update, setdefault, pop, popleft, discard, clear, del self.items[k], rotate, move_to_end, |=, ...;
  • storing an item (self.items[k] = v), which counts for a mapping (the key may be new) but not for a deque, whose iterators allow it;
  • reading a missing key of a defaultdict (self.groups[k].append(v)).

A store or a defaultdict read under a key the container holds adds no key, and does not count: inside if k in self.items:, past if k not in self.items: return or if self.items.get(k) is None: raise KeyError(k), or after a read of self.items[k] in the same block (not for a Counter, whose read of a missing key inserts nothing).

Rebinding the attribute (self.items = {}) changes no container, and the changes a function makes after it binds a new container to the attribute on every path (self.items = {}, then self.items[k] = v) are that new container's, not the one an iteration steps. Changes that a method it calls after the rebinding makes (self.items = {}, then self.add(k)) still count.

What runs while a generator is suspended depends on where its generator object goes:

  • A private generator (_name) runs only where the project iterates it. Between its steps, the body of the loop iterating it runs: the methods of the class that this body calls on the generator's instance count, on the same self, variable, or attribute (self.registry) the generator was called on, also through the functions that hand the generator on. A call that consumes it (list(...), sorted(...)) runs nothing in between, and a generator that suspends inside such a loop is followed in turn.
  • When the generator object outlives one use of it, any public method of the class, its project subclasses, and the bases it inherits from can run in between: it is stored (on the instance, in a list), yielded, or handed to code heki does not follow, or a step that leaves it suspended (next(), send(), a loop that leaves early or over a wrapper that stops first, any(), islice()) is followed by another use of it. Initialization does not count: __init__, __post_init__, __new__, __setstate__, __enter__, setup, and the other two-phase initialization methods MUT101 names run before any iteration. A private method counts through the methods calling it.
  • A public generator, __iter__ included, is an iteration the class offers its callers, as dict.items() is: its public methods that change the container are the rest of that interface, and changing a container while iterating it is the caller's mistake, as for a builtin container. Only the changes made by reads count: property getters and the read dunder methods (__getitem__, __len__, __contains__, ...). The project's own loops over it count as for a private generator.

A change written in the loop's body itself is the linters' check (Ruff's B909 and PLE4703), and not reported. The rule reports one diagnostic per iteration of a suspended generator, at the iteration, naming one changing method and listing each one as a related location, and one per call in a loop's body that changes the container, at the call.

What a report states

A report states that a dict, set, or deque held in self.<attr> is changed in place by code that can run while a method iterates it, so the next step of the iteration raises RuntimeError.

Its premises:

  • Container: the attribute holds one of these containers, by its assignment in __init__ or its annotation (assumption R2).
  • Iterated: a for loop or yield from steps through it, or through a view or lazy wrapper of it. Established.
  • Can run meanwhile: the change is in a function the loop's body calls, or in a method that can run while a generator is suspended in the loop. Open: what can run while a generator is suspended follows where its object goes, as described above, not the calls the program makes.

Why is this bad?

A dict or set iterator raises RuntimeError: dictionary changed size during iteration (or Set changed size during iteration) at its next step after its container gained or lost an item, and a deque iterator raises RuntimeError: deque mutated during iteration after any change but an item store. A generator suspended inside such an iteration fails when it resumes after another method ran, which may be far from both and only for some orders of calls.

Example

class Subscriptions:
    def __init__(self) -> None:
        self.by_node: dict[str, object] = {}
        self._cursor = self._cycle()

    def _cycle(self):
        while True:
            yield from self.by_node.values()  # MUT113

    def next_subscriber(self) -> object:
        return next(self._cursor)

    def drop(self, node: str) -> None:
        self.by_node.pop(node, None)

Use instead:

    def _cycle(self):
        while True:
            yield from list(self.by_node.values())

How to fix

Iterate over a snapshot taken before the loop (list(self.by_node.values())), or collect the changes and apply them after the loop has finished.

Fix safety

No automatic fix: a snapshot no longer sees the items added during the iteration, which can be what the code wants.

Known limitations

  • A list does not count: a list iterator sees the items appended during the iteration and skips or repeats items when others move, without an error.
  • A container of an abstract class (MutableMapping, MutableSet) or of a class heki does not know does not count. A deque() or defaultdict(...) assigned without an annotation has no class for heki: annotate the attribute (self.queue: deque[int] = deque()).
  • An await inside a loop, and threads, are not suspensions the rule follows.
  • A loop's call on another object than the generator's instance does not count, even on another parameter that may be the same object at run time (for k in source._walk(): destination.remove(k) called as copy_over(r, r)).
  • A method returning an iterator or a view instead of being a generator (return iter(self.items)) is not followed, and neither is a generator passed to a project function that iterates it.
  • A generator handed to code heki does not follow counts as outliving the call, also when that code consumes it at once (self.assertCountEqual(gen(), [...])).
  • The tests on the paths to a change are not followed across calls: a change only a lazy initialization makes (if not self.loaded: self._load()) counts although the iterating method ran it first, and so does a change that a constant argument of the call turns off (add(item, check=False) where add changes the container only if check:).