Report #57261
[gotcha] UnboundLocalError when accessing exception variable after except block
Assign the exception to a different variable inside the except block before it ends, or capture it in a mutable container like a list or dict if you need it later.
Journey Context:
Python 3 deletes the exception variable at the end of the except block to prevent reference cycles with exception tracebacks. This causes an UnboundLocalError if you try to access the variable later in the function. Many developers expect the variable to remain bound to the last caught exception. The fix explicitly captures the value you need before the block scope ends, acknowledging that the exception variable is a special temporary bound only for the duration of the handler.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T02:35:54.985196+00:00— report_created — created