iterator-double-consumption (MUT106)¶
Family: Mutation & State (MUT) · Heuristic · Opt-in · Severity error (a bug) · No automatic fix
Opt-in: consuming a single-pass iterator or generator a second time (the second pass sees no items).
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 for a single-pass iterator or generator that is consumed a second time. Once an iterator is exhausted, every further pass over it sees no items, silently.
Single-pass values are:
- generator expressions (
(x for x in xs)); iter,zip,map,filter,enumerate,reversed,heapq.merge, and the single-passitertoolsfunctions (chain,islice,starmap,takewhile,dropwhile,filterfalse,compress,accumulate,groupby,pairwise,batched,zip_longest,product,permutations,combinations,combinations_with_replacement), resolved through imports so a shadowed name is never matched;- calls of project generator functions (from any module);
- parameters and locals annotated
Iterator,Generator,AsyncIterator, orAsyncGenerator(typingorcollections.abc;Iterable,Sequence, andCollectionmay be re-iterable and are not tracked).
A value is consumed by a for loop or comprehension over it, unpacking (a, *rest = it),
yield from, a call that materializes it (list, tuple, set, frozenset, dict, bytes,
bytearray, sum, min, max, sorted, str.join, bytes.join,
dict.fromkeys, list.extend, set.update / union / intersection / difference,
dict.update, collections.deque / Counter / OrderedDict / defaultdict,
heapq.nlargest / nsmallest, functools.reduce, math.prod / fsum), a wrapper that is
itself consumed (enumerate(it), map(f, it), chain(it, other), heapq.merge(it, other),
zip(it, it), a generator expression over it, ...), or a project function that iterates the
parameter it is passed to exhaustion (for a method, every implementation the call may run must;
an @abstractmethod never runs). next(it) and len are not consumptions, and neither are
zip / map over several iterables, islice, or takewhile: they stop at the shortest one or
early (zip(range(n), it) takes n items). The same table decides where a generator's body
runs for the effect and contract rules.
The rule reports the second pass when the first one runs to exhaustion and the second is reachable from it, without rebinding the variable in between. It also reports a value created outside a loop and consumed to exhaustion inside it: the next iteration sees nothing.
It does not report:
- a first pass that may stop early: a
forloop withbreak,return, orraiseinside (it = iter(lines), thenfor line in it: ... break, thenfor line in it:is the idiomatic way to resume), andany(it)/all(it), which stop at the first item that decides the result (they still run a generator's body where they are called); - passes on exclusive branches (
if c: list(it) else: sorted(it)); - a variable rebound to a fresh iterator in between;
itertools.teeresults,repeat,cycle, andcount;- loops that run at most once (
for _ in range(1)), and a consumption followed by leaving the loop (data = list(it)thenbreak); - consuming the rest of an iterator inside a loop over that iterator itself.
What a report states¶
A report states that a single-pass iterator is consumed a second time after a full first pass, so the second pass sees no items.
Its premises:
- Single-pass: the value is one of the iterators listed above. Established from its construction or annotation.
- Full first pass: the first consumption exhausts it. Established: partial passes (
break,any/all,next()) do not count. - Second pass after it: the second consumption is reachable from the first. Open: reachable means some path of the control flow, which the code may never take.
Why is this bad?¶
The second pass silently gets an empty iterator: totals become zero, a second report is empty, and a retry processes nothing. Nothing fails, so the bug is noticed far away from its cause.
Example¶
def summarize(lines: list[str]) -> tuple[int, list[str]]:
rows = (line.strip() for line in lines)
count = sum(1 for _ in rows)
kept = [r for r in rows if r] # MUT106: `rows` was consumed by `sum`
return count, kept
Use instead:
def summarize(lines: list[str]) -> tuple[int, list[str]]:
rows = [line.strip() for line in lines] # a list can be iterated any number of times
count = len(rows)
kept = [r for r in rows if r]
return count, kept
Fix safety¶
No automatic fix.
Options¶
lint.extend-select = ["MUT106"](or--extend-select MUT106) enables the rule. It is opt-in: selecting theMUTprefix does not enable it.