Running this code prints 2.
x = 2
def foo():
print(x)
foo()
However, running this code returns an UnboundLocalVariable exception when I attempt to print x. (Line 3).
x = 2
def foo():
print(x)
x = 10
foo()
Python is an interpreted language, so I don't understand how it can 'know' that I will assign x a value as a local variable on line 5, when it gives an error on line 4. Is there some sort of pseudo-compiling when I define the function?
In python, variable definition is attached to the scope that it's in. In this example,
xis attached to the scope offooat the timefoois compiled. Python gives you anUnboundLocalErroron line 3 becausexis attached tofoo's scope but has not been bound yet. The same error can be seen if no globalxis present:Exploring further, we can see that when compiling line-by-line (outside of a function, in the interactive REPL), python can't look ahead to see if
xwill be defined:And we get a
NameErrorinstead.UnboundLocalErroris a subclass ofNameErrorbecause it indicates the same problem, just with a more helpful name and message.