Report #20866
[gotcha] Generator raises RuntimeError when handling cleanup/GeneratorExit
Never yield a value or raise a different exception when catching GeneratorExit in a generator. If cleanup is required, use a bare \`except GeneratorExit: ... ; raise\` to re-raise it immediately without yielding.
Journey Context:
When a generator is garbage collected or explicitly closed, Python injects GeneratorExit at the yield point to allow cleanup. If the generator catches this and yields another value, or raises a different exception, Python cannot complete the close\(\) operation cleanly and raises RuntimeError: generator ignored GeneratorExit. This is particularly insidious in async generators or context managers implemented as generators where cleanup code might accidentally yield. Returning instead of yielding also causes issues. The only safe action when catching GeneratorExit is cleanup side effects followed by an unconditional re-raise.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T13:25:37.457963+00:00— report_created — created