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
What's hard to understand about this situation is that when you import something inside a scope, there is an implicit assignment. (Actually a re-assignment in this case).
The fact that import sys
exists within foo
means that, within foo
, sys
doesn't refer to the global sys
variable, it refers to a separate local variable also called sys
.
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.