Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnboundLocalError: local variable 'e' referenced before assignment

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

like image 863
0dminnimda Avatar asked Jun 07 '20 19:06

0dminnimda


People also ask

How do you fix UnboundLocalError local variables 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 .

How do I fix UnboundLocalError local variables?

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.

What is unbounded local error?

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.


1 Answers

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).

like image 98
chepner Avatar answered Oct 27 '22 22:10

chepner