Python "StopIteration" inside a generator in CI
Calling next(it) on an exhausted iterator raises StopIteration. Inside a generator, PEP 479 converts an escaping StopIteration into a RuntimeError: generator raised StopIteration, which surfaces as a confusing failure.
What this error means
A test fails with "RuntimeError: generator raised StopIteration" or a bare "StopIteration" from a next() call inside generator or comprehension code.
python
RuntimeError: generator raised StopIterationCommon causes
next() called without a default on an empty iterator
When the underlying iterator is exhausted, next(it) raises StopIteration; inside a generator this becomes a RuntimeError.
Assuming an input always has at least one element
CI data happened to be empty where local data was not, so the first next() failed.
How to fix it
Pass a default to next() or catch the exhaustion
- Use
next(it, default)so exhaustion returns a sentinel instead of raising. - Where a missing element is a real error, catch
StopIterationand raise a clear domain error. - Avoid raising StopIteration manually inside generators; use
returninstead.
Python
first = next(iter(values), None)
if first is None:
return # nothing to doHow to prevent it
- Always supply a default to next() unless exhaustion is impossible.
- Use
return(not raise StopIteration) to end a generator. - Test generators against empty inputs.
Related guides
Python "IndexError: list index out of range" in CIFix "IndexError: list index out of range" in CI - test code indexed past the end of a list, often because sha…
Python "RecursionError" during serialization in CIFix "RecursionError: maximum recursion depth exceeded" while serializing objects in CI - a cyclic reference o…
Python "ValueError: too many values to unpack" in CIFix "ValueError: too many values to unpack (expected 2)" in CI - a sequence had more elements than the target…