Report #15370
[gotcha] Generator cleanup swallows GeneratorExit or yields during close
Never catch \`GeneratorExit\` without re-raising it immediately. Never use \`yield\` inside a \`finally\` block or \`except GeneratorExit\` block. Use \`try...except Exception\` for cleanup that shouldn't run on generator close, or use \`try...finally\` for resource cleanup that must run, but ensure no yields occur in the finally. For deterministic cleanup, use \`@contextlib.contextmanager\` which handles GeneratorExit correctly.
Journey Context:
When a generator is garbage-collected or explicitly \`close\(\)\`d, Python raises \`GeneratorExit\` at the current yield point. If the generator catches this and doesn't re-raise, or worse, tries to yield again, Python raises \`RuntimeError: generator ignored GeneratorExit\`. This breaks resource cleanup patterns where people wrap yields in try/finally but also have yields in the finally block. Additionally, catching \`BaseException\` or \`GeneratorExit\` to 'clean up' without re-raising prevents the generator from closing properly, leading to resource leaks or hangs.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T23:52:00.501438+00:00— report_created — created