Report #55633
[gotcha] RuntimeError: generator raised StopIteration when manually advancing iterators inside generators
Never raise StopIteration explicitly inside a generator function; use return instead. When wrapping iterators, catch StopIteration and return the value, or use yield from. If you must manually drive an iterator, wrap the logic in a separate helper function that is not a generator.
Journey Context:
Before PEP 479 \(Python 3.5\+\), raising StopIteration inside a generator would simply stop the generator, which was often accidental when calling next\(\) on an exhausted iterator inside the generator. This silently swallowed bugs. Now, StopIteration raised inside a generator is converted to RuntimeError to prevent accidental suppression. The confusion arises because 'return' in a generator raises StopIteration under the hood, but explicit raise or accidental leakage from next\(\) is banned. The fix requires refactoring: if you have a generator that manually calls next\(it\) and catches StopIteration to break, you must either move that logic to a non-generator function or use yield from.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T23:52:28.166826+00:00— report_created — created