UnboundLocalError: local variable referenced before assignment
The UnboundLocalError: local variable referenced before assignment
occurs when you reference a local variable before assigning any value to it inside a function.
The UnboundLocalError
can be resolved by changing the variable's scope to global using the global
keyword inside the function definition.
How to Reproduce the Error
Following is a simple example of reproducing the UnboundLocalError
in Python.
# declare variable
text = "Tutorial"
def print_text():
print(text)
text = "Python Tutorial"
print_text()
Output
UnboundLocalError: local variable 'text' referenced before assignment
Python does not have a variable declaration. Hence it determines the variable's scope when you assign a value to it.
If you assign a value to a variable inside a function, then it's considered a local scope; otherwise, it's considered a global scope.
In the above example, we have created a variable text
outside the function, which is a global variable.
We also have created a local variable text
and assigned a value inside the function print_text()
that shadows the global variable scope, and hence it results in UnboundLocalError: local variable 'text' referenced before assignment
.
How to Fix the Error
Solution 1: Change the scope of the variable to global
The global variables created can be accessed inside a function, but you cannot change or modify its value unless you change the variable's scope.
In our example, we were modifying the value of a global variable inside a function which resulted in UnboundLocalError
To resolve the error, simply mark the variable as global
inside the function, which changes the variable's scope.
# declare variable
text = "Tutorial"
def print_text():
# change the scope to global
global text
print(text)
text = "Python Tutorial"
print_text()
print_text()
Output
Tutorial
Python Tutorial
Solution 2: Passing global variable as an argument to the function
The alternate solution is to pass the global variable as an argument to the function, as shown below.
# declare variable
text = "Tutorial"
def print_text(text):
print(text)
text = "Python Tutorial"
print_text(text)
Output
Tutorial
Rules for Global and Local variables in Python
To avoid UnboundLocalError
you should also know the general guidelines of local and global variables in Python.
- In Python, variables that are only referenced inside a function are implicitly global.
- If the value is assigned to a variable inside a function, then the scope changes to local unless it's explicitly declared as global.
Conclusion
In Python, UnboundLocalError: local variable referenced before assignment
occurs when you reference a local variable before assigning any value to it inside a function.
To solve the error, you need to make it a global variable inside a function or pass the global variable as a function argument to the method.