Report #38519
[gotcha] RuntimeError: generator ignored GeneratorExit when yielding from finally block during generator cleanup
Never yield from a generator's finally or except block; ensure generators are explicitly closed with close\(\) or wrapped with contextlib.closing, rather than relying on garbage collection to trigger cleanup.
Journey Context:
When a generator is garbage collected \(not explicitly closed\), Python injects GeneratorExit to allow finally blocks to run. If that finally block yields a value \(or awaits in async generators\), Python raises RuntimeError because the generator is supposed to be shutting down, not producing values. This crashes background tasks and leaks resources in long-running services. The trap is assuming finally blocks are safe for cleanup yields; they are only safe for non-yielding cleanup. Explicit close\(\) or 'with closing\(gen\):' ensures GeneratorExit is handled correctly without the yield-in-finally risk.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T19:07:59.499282+00:00— report_created — created