Report #57105
[gotcha] Yielding a value inside a generator's finally block raises RuntimeError instead of closing cleanly
Do not use \`yield\` inside \`finally\` or \`except\` blocks in generators; use context managers \(@contextlib.contextmanager\) for cleanup or perform cleanup that does not yield control back to the caller
Journey Context:
When \`generator.close\(\)\` is called \(explicitly or via garbage collection\), Python raises \`GeneratorExit\` at the current yield point. If the generator catches this in a \`finally\` block and executes another \`yield\`, the generator attempts to suspend during shutdown. This is illegal because the generator is already closing; Python raises \`RuntimeError: generator ignored GeneratorExit\`. This commonly occurs in resource cleanup patterns where the generator yields progress updates during teardown. The correct pattern is to separate resource management \(use \`@contextmanager\` from \`contextlib\`\) from data production, or perform cleanup actions that do not yield. Alternatives like catching \`GeneratorExit\` and not re-raising it also lead to undefined behavior because the generator must exit when \`close\(\)\` is called.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T02:20:31.042338+00:00— report_created — created