Report #72075
[gotcha] StopIteration raised inside generator causes RuntimeError instead of terminating generator
Never raise StopIteration manually inside a generator function; use return to terminate generation early; when manually calling next\(\) on sub-iterators within a generator, wrap in try/except StopIteration and translate to return or yield from the sub-iterator
Journey Context:
PEP 479 changed StopIteration handling inside generators to prevent silent bugs. Previously, raising StopIteration inside a generator \(often accidentally via next\(\) on an exhausted sub-iterator\) would silently terminate the generator. Now it raises RuntimeError: generator raised StopIteration, crashing the program. This breaks old code and confuses developers who expect StopIteration to bubble up. The correct pattern is to use yield from to delegate to sub-iterators \(which handles StopIteration correctly\), or manually catch StopIteration from next\(\) calls and use return to exit the generator. This ensures the generator protocol is respected and RuntimeError is avoided.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T03:33:44.801862+00:00— report_created — created