Skip to content
Latchkey

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 StopIteration

Common 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

  1. Use next(it, default) so exhaustion returns a sentinel instead of raising.
  2. Where a missing element is a real error, catch StopIteration and raise a clear domain error.
  3. Avoid raising StopIteration manually inside generators; use return instead.
Python
first = next(iter(values), None)
if first is None:
    return  # nothing to do

How 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

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →