Why is the variable used in the exception being deleted
Why is the variable used in the statement except
being deleted? I mean:
x = 0
try:
x = 5/0
except ZeroDivisionError as x:
pass
print(x)
I get NameError: name 'x' is not defined
why is this? Can't it work both with def
or with the understanding where if there is a variable with the same variable name in the closing function (or module) it is just dimmed but not removed?
This is explained in the documentation (parts in [] brackets added by me):
When an exception is assigned with
as target
[i.e.as x
in your case] , it is cleared at the end of the except clause. It's as if
except E as N:
foo
was translated to:
except E as N:
try:
foo
finally:
del N
This means that the exception must be assigned to a different name in order to be able to refer to it [i.e. this is the name
x
in your case] after the except clause.
The reason for this is also:
Exceptions are cleared because when you attach traces to them, they form a reference loop with a stack frame, keeping all locales in that frame until the next garbage collection occurs.
The behavior is registered here :
When an exception is assigned as a target, it is cleared at the end of the except clause.
This means that the exception must be assigned to a different name in order to be able to reference it after the except clause. Exceptions are cleared because when you attach a trace to them, they form a reference loop with a stack frame, keeping all locales in that frame until the next garbage collection occurs.