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.
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:
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)