Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnboundLocalError on nested module reimport

Tags:

python

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.

like image 510
Tomáš Čechal Avatar asked Dec 16 '15 12:12

Tomáš Čechal


People also ask

How do you fix UnboundLocalError?

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 does UnboundLocalError mean in Python?

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?

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.


1 Answers

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.

like image 113
pacholik Avatar answered Sep 28 '22 07:09

pacholik