The following program throws UnboundLocalError
but I don't understand why.
It's a very condensed version of a nasty bug found in one of my scripts.
EDIT: I don't accept the explanation of "variable hoisting". I don't think this actually happens in Python. If the function namespace is printed, it shows that pickle
does not exist locally. Going by the LEGB lookup rules, Python should find the pickle
name in the global namespace.
Sometimes it takes a while to frame the question. I guess the real question is why. I understand what is happening, but why does Python do this? Why does Python break its own LEGB lookup rules?
import pickle
def func(number):
print("Global variables=%s" % repr(globals()))
print("Local namespace=%s" % repr(dir()))
dir(pickle) # This line will fail
import pickle # This line is the cause of the failure.
return number
func(5)
Program output:
Global variables={'__builtins__': <module '__builtin__' (built-in)>, '__file__': 'c:\\python27\\globaltext.py', '__package__': None, 'func': <function func at 0x02320E70>, '__name__': '__main__', 'pickle': <module 'pickle' from 'C:\Python27\lib\pickle.pyc'>, '__doc__': None}
Local namespace=['number']
Traceback (most recent call last):
File "test.py", line 8, in <module>
func(5)
File "test.py", line 4, in func
dir(pickle) # This line will fail
UnboundLocalError: local variable 'pickle' referenced before assignment