UnboundLocalError on nested module reimport

后端 未结 2 515
刺人心
刺人心 2021-01-18 10:10

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         


        
相关标签:
2条回答
  • 2021-01-18 11:02

    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.

    0 讨论(0)
  • 2021-01-18 11:12

    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.

    0 讨论(0)
提交回复
热议问题