Report #46752
[gotcha] NameError when accessing exception variable after except block in Python 3
Assign the exception to a different variable inside the except block before exiting, use \`sys.exc\_info\(\)\` if deferred access is needed, or wrap the exception in a custom object. Do not reference the \`as e\` variable after the block ends.
Journey Context:
Python 3 changed exception scoping to prevent reference cycles \(the exception holds the traceback, which holds stack frames, which might reference the exception\). In Python 2, \`except Exception as e\` leaked into surrounding scope. In Python 3, the variable is deleted at block end. Developers often try to log \`e\` after the try/except or return it from a function, triggering NameError. The alternatives are explicit assignment to another variable that survives the block, or using \`sys.exc\_info\(\)\` inside the handler to capture details for later use.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T08:56:58.957458+00:00— report_created — created