Any variable you assign to inside a scope is treated as a local variable (unless you declare it global
, or, in python3, nonlocal
), which means it is not looked up in the surrounding scopes.
A simplified example with the same error:
def a(): pass
def b(): a = a()
Now, consider the different scopes involved here:
The global namespace contains a
and b
.
The function a
contains no local variables.
The function b
contains an assignment to a
- this means it is interpreted as a local variable and shadows the function a
from the outer scope (in this case, the global scope). As a
has not been defined inside of b
before the call, it is an unbound local variable, hence the UnboundLocalError. This is exactly the same as if you had written this:
def b(): x = x()
The solution to this is simple: choose a different name for the result of the sub
call.
It is important to note that the order of use and assignment makes no difference - the error would have still happened if you wrote the function like this:
def display():
value = sub(2,1) #UnboundLocalError here...
print value
sub = "someOtherValue" #because you assign a variable named `sub` here
This is because the list of local variables is generated when the python interpreter creates the function object.