In Python, when a variable is used before it has been defined or assigned some value, the interpreter throws an
UnboundLocalError exception. In this tutorial, we get to learn several ways to fix the
UnboundLocalError exception in Python.
Referenced Before Assignment Error in Python
A general approach to solving this issue would be to ensure that whatever variables we are using can be accessed in the current scope. They are declared and assigned some value before being used anywhere.
To understand this better, refer to the following Python code.
def function(): x = x + 1 x = 10 function()
Traceback (most recent call last): File "<string>", line 5, in <module> File "<string>", line 2, in function UnboundLocalError: local variable 'x' referenced before assignment
We got the
UnboundLocalError error in the above code. The reason behind this can be found in the statement:
x = x + 1.
As we can see, we are using the old value of
1 to it, and then storing the new value back to the variable
x. But we have not declared and defined the variable
x anywhere inside the function
We have defined the variable
x outside the function, but it can not be accessed yet because it’s out of the
function() scope. To fix this issue, we can either declare and define the variable
x inside the
function() method or use the
x outside the
function() method with the help of the
We can also modify the
function() method and add an argument
x to it. Refer to the following Python code for the first solution.
def function(): x = 100 print(x) x = x + 1 print(x) x = 10 print(x) function() print(x)
10 100 101 10
We declared a local variable in the above code
x inside the
function() method and assigned
100 to it. Furthermore, we incremented its value by
The output shows that only the local variable
x was modified inside the function, and the variable
x outside the function remains untouched. Refer to the following Python code for the second solution.
def function(): global x x = x + 1 x = 10 print(x) function() print(x)
We did not declare any variable inside the
function() method in the above code.
Instead, we are accessing the variable
x outside the function with the help of the
global keyword. We can access the output that the variable
x value is getting modified for the output.
Finally, let’s see how we can solve this issue by modifying the function signature and adding an argument. Refer to the following Python code for the discussed approach.
def function(x): x = x + 1 print(x) x = 10 print(x) function(x) print(x)
10 11 10
As we can see, now we are accessing the argument
x value. We are modifying the value of the argument, and from the output, we can access that the value of the variable
x outside the
function() method remains untouched.