osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Catching an exception in a variable


"ast" <nomail at com.invalid> writes:

> Why variable ex doesn't exist ?

Because of a deliberate decision made to delete it. Silently.

This is documented:

    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.

    <URL:https://docs.python.org/3/reference/compound_stmts.html#the-try-statement>

but I think this is a terrible idea. It silently deletes a name binding
from the current scope, without the code explicitly asking for that.

-- 
 \     ?For certain people, after fifty, litigation takes the place of |
  `\                                                 sex.? ?Gore Vidal |
_o__)                                                                  |
Ben Finney