Report #41006
[gotcha] Exception variable 'e' deleted after except block in Python 3
Assign the exception to a different variable name inside the except block if you need it later \(e.g., \`caught = e\`\), or return it immediately. Do not reference 'e' after the except block ends.
Journey Context:
Python 3 introduced exception target variable deletion at the end of the except clause \(PEP 3110\) to break reference cycles between the exception object, its traceback, and the frame. Developers often assume 'e' behaves like a regular variable assigned inside the block, but the compiler explicitly unbinds the name at block exit. This manifests as a mysterious NameError when attempting to log or re-raise the exception later in the function. The workaround requires explicitly capturing the reference in a variable that is not the exception target.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T23:18:02.869891+00:00— report_created — created