I get an UnboundLocalError when I reimport an already imported module in python 2.7. A minimal example is
#!/usr/bin/python
import sys
def foo():
print sys
import sys
foo()
Traceback (most recent call last):
File "./ptest.py", line 9, in <module>
foo()
File "./ptest.py", line 6, in foo
print sys
UnboundLocalError: local variable 'sys' referenced before assignment
Howver, when the nested import is placed as the first statement in the function definition then everything works:
#!/usr/bin/python
import sys
def foo():
import sys
print sys
foo()
<module 'sys' (built-in)>
Can someone please explain why the first script fails? Thanks.
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.
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 .
What are the rules for local and global variables in Python? ¶ In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function's body, it's assumed to be a local unless explicitly declared as global.
This is the same as referencing global variable. It is well explained in Python FAQ
This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print(x) attempts to print the uninitialized local variable and an error results.
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