Python 3 exception deletes variable in enclosing scope for unknown reason [duplicate] Python 3 exception deletes variable in enclosing scope for unknown reason [duplicate] python-3.x python-3.x

Python 3 exception deletes variable in enclosing scope for unknown reason [duplicate]


Quoting the documentation of try,

When an exception has been assigned using as target, it is cleared at the end of the except clause. This is as if

except E as N:   foo

was translated to

except E as N:    try:        foo    finally:        del N

This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs.

This is covered in these two PEPs.

  1. PEP 3110 - Catching Exceptions in Python 3000

  2. PEP 344 - Exception Chaining and Embedded Tracebacks