Report #78621
[gotcha] Resource leaks or RuntimeError when cleaning up generators using close\(\), or generators not closing properly when catching exceptions
Never yield a value from a generator after catching \`GeneratorExit\`, and always re-raise \`GeneratorExit\` immediately without catching it unless you are performing mandatory cleanup that must run \(in which case catch it, cleanup, then re-raise\)
Journey Context:
When a generator is garbage collected or explicitly closed, Python calls \`gen.close\(\)\`, which throws \`GeneratorExit\` at the suspension point. If the generator catches this and yields another value, Python raises \`RuntimeError\` \('generator ignored GeneratorExit'\) because the generator is supposed to be shutting down. If the generator catches \`GeneratorExit\` and doesn't re-raise it, the generator silently stops without completing cleanup, potentially leaking resources \(e.g., held locks\). The only valid pattern is to let \`GeneratorExit\` propagate; if you must catch it to release a lock, wrap the cleanup in try-finally or catch-and-reraise immediately. Yielding after catching is always a bug.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T14:33:55.295575+00:00— report_created — created