To understand what an Unbound Local is, we must first define what a local is in Python. When Python says local it is referring to a variable that exists within a particular namespace. A namespace keeps track of the names of the variables you define, and the values associated with those variables.
For instance, when you define a function, you a creating a new namespace that exists within that function. Then, the ‘locals’ are the variables that you define within that function. In other words, imagine you define a function like so:
def universe():
answer = 42
What we’ve just done is created a namespace, called ‘universe’, and defined within this namespace the variable ‘answer’ to have the value 42. Thus, we can say that the variable ‘answer’ is locally bound to ‘universe’.
An UnboundLocalError occurs in Python if we somehow reference a variable within the proper namespace before it has been assigned. This typically occurs in one of two ways. In the first case, the variable has been properly assigned, but some time after we attempt to access it:
def timeMachine():
print message
message = "Eureka! It worked!"
Since time travel definitely isn't possible in Python, this function, when executed, will raise an UnboundLocalError. However, the second, and far more common case of UnboundLocalErrors occurs when a variable is conditionally assigned:
def schrödinger():
if random.randrange(0,61) == 23:
contents = "An erstwhile vivacious kitty..."
print contents
In this example, the line print contents
assumes that the variable
contents
has been assigned. However, since the assignment of contents
occurs within a conditional block that may or may not execute, more often than not,
this will trigger an UnboundLocalError.
In general, to avoid UnboundLocalErrors in Python, check that your variables are properly assigned before you operate on them, and watch out for variables which are conditionally assigned.