End `itertools.chain` when an argument fails

Merged
RE
4mo ago
+119-16

Fixes itertools.chain so that when an argument fails iter(), the chain is permanently exhausted (raising StopIteration afterwards, as CPython does) instead of silently skipping the bad argument and continuing into the next one

Expected behaviour (CPython):

c = chain([1], 5, [2, 3])
next(c) 
next(c) # TypeError
next(c) # StopIteration

Fix - set chain_mut(iter, vm).done = true as we propagate the error


Summary by cubic

End itertools.chain when an argument fails iter() and clear its sources when the chain ends, matching CPython. Previously the chain skipped the bad argument and continued; now it raises TypeError once and is then exhausted (StopIteration), and it releases its arguments so a spent chain does not pin them.

  • Set the chain’s done latch in into_py_iter_tracking on iter() failure and call finish to take and drop sources and current; later arguments are never reached and subsequent next() calls return StopIteration.
  • Preserve the asymmetry: if a resolved source’s __next__ raises, the chain stays live and surfaces the same error on the next call.
  • Add tests for both behaviors and for GC/refcount: a spent chain releases its arguments on both endings (draining the last source and iter() failure), including cycles.
  • Refactor: introduce chain_mut to avoid repeated matches and finish to centralize chain teardown; no functional change beyond the new latch and releases.