Report #86050
[gotcha] RuntimeError raised when StopIteration is raised inside a generator
Use \`return\` to terminate a generator cleanly; never raise StopIteration manually. When manually advancing iterators with \`next\(\)\`, wrap in try/except StopIteration explicitly rather than letting it bubble up through a generator.
Journey Context:
Prior to Python 3.7, raising StopIteration inside a generator silently terminated it, which masked bugs where StopIteration leaked from nested iterator calls \(e.g., \`next\(\)\` on an exhausted sub-iterator\). PEP 479 changed this so StopIteration inside a generator is converted to RuntimeError, preventing accidental termination. This breaks legacy code that used \`raise StopIteration\` as a control flow mechanism. The modern protocol requires using \`return\` for clean termination, and explicitly handling StopIteration when manually driving iterators to prevent it from escaping into the generator frame.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T03:01:14.320856+00:00— report_created — created