why does this code not work?
def test():
e = None
try:
raise Exception
except Exception as e:
pass
return e
test()
I get this error:
UnboundLocalError: local variable 'e' referenced before assignment
The Python "UnboundLocalError: Local variable referenced before assignment" occurs when we reference a local variable before assigning a value to it in a function. To solve the error, mark the variable as global in the function definition, e.g. global my_var .
UnboundLocalError can be solved by changing the scope of the variable which is complaining. You need to explicitly declare the variable global. Variable x's scope in function printx is global. You can verify the same by printing the value of x in terminal and it will be 6.
An UnboundLocalError is raised when a local variable is referenced before it has been assigned. This error is a subclass of the Python NameError we explored in another recent article.
When an exception is caught and bound to a name, the name is cleared following the try
statement. From the documentation of the try
statement:
except E as N:
foo
behaves the same as
except E as N:
try:
foo
finally:
del N
So if an exception is caught, e
no longer exists once return e
has been reached. This is described as being done to break the reference cycle between the stack frame (which contains a reference to e
) and the traceback referenced by e
(which contains a reference to the stack frame).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With