UnboundLocalError in Python with Example
UnboundLocalError in Python occurs when variable is identified as Local but it is used prior of creation.
This article explains UnboundLocalError with Example.
Consider a following simple Python program in which variable var is created in global scope and accessed from my_function
:
var = 20 # var is global variable
def my_function():
print(var) # It access global
my_function() # Calling function
Output
20
Above output is straight forward and is expected.
But, when we have assignment for var within my_function
after print
then things will be different. See following python program which illustrates UnboundLocalError:
# UnboundLocalError in Python
var = 20 # a is global variable
def my_function():
print(var)
var = 'Hello' # This causes UnboundLocalError
print(var)
my_function() # Calling function
Output
UnboundLocalError: local variable 'var' referenced before assignment
So, what happened here? When we create & execute function definition def my_function():
, without calling it, it does not create any local scope for my_function
.
Creating local scope for my_function
in this example happens at compile time. At compile time Python sees var = 'Hello'
which is creating local variable var
. So Python determines var will be local but at the same time it also sees print(var)
which is used before assignment. Which means variable var is local but not yet bounded or created giving UnboundLocalError but it is determined that var will be local.