Report #79910
[gotcha] Generator silently ignores close\(\) or context manager exit due to catching GeneratorExit
Never catch GeneratorExit with bare \`except:\` or \`except Exception:\`. If you must catch it \(e.g., for cleanup\), always re-raise it explicitly with \`raise\`.
Journey Context:
When a generator or async generator is garbage collected or explicitly closed, Python injects GeneratorExit at the yield point to allow cleanup. If the generator catches this with a broad exception handler and doesn't re-raise, the close operation appears to succeed but the generator actually resumes execution, potentially causing resource leaks or infinite loops. The correct pattern is to treat GeneratorExit like KeyboardInterrupt: catch only if you must perform cleanup, then immediately re-raise. This ensures the generator protocol completes correctly.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T16:43:43.019207+00:00— report_created — created