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.