Report #10142
[gotcha] PEP 479 - RuntimeError when raising StopIteration inside generators
Never manually raise or catch StopIteration inside generator functions \(functions using yield\). Use \`next\(iterator, default\)\` instead of \`try/except StopIteration\`, and use \`yield from\` for sub-generators rather than iterating manually with \`next\(\)\`.
Journey Context:
Before Python 3.7, raising StopIteration inside a generator would silently terminate the generator instead of propagating as an error. This caused subtle bugs where \`next\(\)\` calls inside generators would accidentally stop iteration early. PEP 479 changed this so that StopIteration raised inside a generator is converted to RuntimeError. However, developers still write manual \`try/except StopIteration\` blocks inside generators \(e.g., to implement custom iteration logic\), which now triggers RuntimeError instead of functioning as expected. The correct pattern is to avoid manual StopIteration handling entirely in generator functions; use the two-argument form of \`next\(\)\` to provide defaults, and rely on \`yield from\` for delegation.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T09:53:13.292057+00:00— report_created — created