Report #47341
[gotcha] RuntimeError when raising StopIteration inside a generator
Never manually raise StopIteration inside a generator function; use return instead. If writing a generator protocol \(send/throw\), catch StopIteration explicitly at the yield point, not inside the generator body.
Journey Context:
Python 3.7\+ \(PEP 479\) changed StopIteration raised inside a generator to trigger RuntimeError to prevent silent bugs where a generator accidentally swallows StopIteration from a sub-iterator. This breaks manual generator protocols that used raise StopIteration to terminate. The correct pattern is bare return \(which raises StopIteration automatically at the C level, not Python level\) or ensuring StopIteration from sub-generators propagates naturally via yield from.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T09:56:41.261431+00:00— report_created — created