6

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.

  • If you remove import sys from the function, then also it will work. As there is no sys in the scope of foo() and it will refer to the sys from global scope. – manishrw Dec 16 '15 at 12:44

2 Answers2

1

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.

pacholik
  • 8,607
  • 9
  • 43
  • 55
1

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.

cowlinator
  • 7,195
  • 6
  • 41
  • 61