Mastery
Mastery/Python/B. Iteration & generators
T2 · intermediate depth

PEP 479: StopIteration raised inside a generator becomes RuntimeError

Before Python 3.7, a StopIteration accidentally raised inside a generator's body would silently look identical to the generator finishing normally -- a real, hard-to-find bug class (a forgotten edge case deep in a generator would just quietly truncate a sequence). PEP 479 fixed it: any StopIteration propagating out of a generator's frame is converted into a RuntimeError, turning a silent truncation into a loud, debuggable crash.

python
def broken_gen():
    yield 1
    raise StopIteration("oops -- manually raised, or could come from calling next() on an exhausted iterator")
    yield 2   # never reached either way

try:
    list(broken_gen())
except RuntimeError as e:
    print("StopIteration raised INSIDE a generator becomes RuntimeError:", e)

This matters most when a generator calls next() on something else and forgets to catch the resulting StopIteration itself -- easy to do by accident, and PEP 479 makes the mistake visible instead of silently truncating output:

python
def accidentally_forwards_stopiteration(it):
    while True:
        yield next(it)   # once `it` is exhausted, next(it) raises StopIteration -- and PEP 479 catches that

try:
    list(accidentally_forwards_stopiteration(iter([1, 2, 3])))
except RuntimeError as e:
    print("caught the same way:", e)

Interview angle

A niche but revealing question for anyone claiming deep Python knowledge: "what happens if a StopIteration gets raised inside a generator body?" Most working Python developers have never hit this directly, so a correct answer (it becomes a RuntimeError, by design, since PEP 479) is a strong signal of having actually read language-change proposals, not just the day-to-day API surface.

In the industry

This mostly matters as a debugging aid rather than something anyone codes around deliberately — the whole point of PEP 479 was converting a silent, hard-to-notice bug (a generator that quietly truncates instead of crashing) into a loud, obvious one. In practice it surfaces most often when a generator calls next() on another iterator and forgets to handle its exhaustion explicitly, which the RuntimeError now catches immediately instead of producing mysteriously short output three functions away.