Report #75397
[gotcha] Manually raising StopIteration inside a generator function silently terminates the generator instead of propagating
Never raise StopIteration explicitly inside a generator; use return or let the generator fall off the end. If you must signal termination in a custom iterator protocol, catch StopIteration and raise RuntimeError or use a sentinel value.
Journey Context:
Before PEP 479 \(Python 3.5\+\), raising StopIteration inside a generator simply halted the generator, which was indistinguishable from natural exhaustion. This allowed bugs where a StopIteration raised accidentally \(e.g., from a sub-generator or helper function\) would silently truncate the generator output, causing data loss. PEP 479 changed this so StopIteration raised inside a generator is converted to RuntimeError, preventing silent data loss, but legacy code or manual iterator implementations that relied on the old behavior now crash or require refactoring to use return statements instead.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T09:09:27.689538+00:00— report_created — created