Table of Contents
ToggleUnboundlocalerror local variable referenced before assignment is a common error when we are dealing with variable scope within functions. The cause of the error is referring to a local variable before it has been assigned a value. In this blog we will see the error code snippet with Unboundlocalerror local variable referenced before assignment and see how to resolve the error.
Figuring UnboundLocalError
Variables in Python have different scopes i.e. local and global. A local variable is defined within a function and can be only accessed inside that function. But in the case of a global variable, It is defined outside any function and accessed anywhere in the code. The UnboundLocalError arises when Python determines that a variable is local but attempts to access it before it has been initialized.
Common Causes of UnboundLocalError local variable referenced before assignment
Variable Assignment Inside Functions:
While creating a function, when we assign a variable within a function, Python treats it as a local variable. If we try to reference this variable before assigning it, we will encounter an UnboundLocalError.
The following code has a variable x which was accessed before it was assigned causing an UnboundLocalError.
def example_function(): print(x) # Trying to access 'x' before assignment x = 10 example_function()
Output
UnboundLocalError Traceback (most recent call last) in () 2 print(x) # Trying to access 'x' before assignment 3 x = 10 ----> 4 example_function() in example_function() 1 def example_function(): ----> 2 print(x) # Trying to access 'x' before assignment 3 x = 10 4 example_function() UnboundLocalError: local variable 'x' referenced before assignment
Solution : Initialize variables in function before we are accessing them in further code
def example_function(): x = 10 print(x) example_function()
Output
10
Nested Functions
When we have a nested function and the inner function tries to access a variable from the outer function without properly declaring it. Which lead to
local variable referenced before assignment error.
def outer_function(): x = 10 def inner_function(): print(x) # Accessing 'x' from outer function x = 20 # This creates a local 'x' inner_function() outer_function() # Raises UnboundLocalError
In the above code we have a function “outer_function” that contains a variable x = 10 and an “inner_function”. Inside inner_function, it attempts to print x and then reassign x = 20. However, since x is reassigned inside “inner_function”, Python treats it as a local variable. Therefore, when trying to print x, Python raises an UnboundLocalError because x is considered local and has not been assigned a value yet in that scope.
Output
--------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) in () 5 x = 20 # This creates a local 'x' 6 inner_function() ----> 7 outer_function() # Raises UnboundLocalError 1 frames in inner_function() 2 x = 10 3 def inner_function(): ----> 4 print(x) # Accessing 'x' from outer function 5 x = 20 # This creates a local 'x' 6 inner_function() UnboundLocalError: local variable 'x' referenced before assignment
Solution :
We can use nonlocal statement which allows us to modify a variable in an outer scope, but non-global scope.
def outer_function(): x = 10 def inner_function(): nonlocal x # This refers to the 'x' from the outer function print(x) # This will print 10 x = 20 # This modifies the 'x' from the outer function inner_function() outer_function()
Output
10
Global Variable Modification
When we try to modify a global variable inside a function without declaring it as global inside our function, Python treats it as a local variable which leads to an UnboundLocalError as when we attempt to use it before assignment.
Let’s understand it with an example. I have initialized a variable x as a global variable. When we are trying to modify a variable inside my function “modify_global()” it throws a UnboundLocalError. The “modify_global” function looks for variable ‘x’ inside local scope as it is not able to find it throws an error.
x = 5 def modify_global(): x += 1 # Trying to modify 'x' without declaring it as global print(x) modify_global() # Raises UnboundLocalErrorOutput
--------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last)Solution : To solve the error we have to define x as global inside the function.in () 5 print(x) 6 ----> 7 modify_global() # Raises UnboundLocalError | in modify_global() 2 3 def modify_global(): ----> 4 x += 1 # Trying to modify 'x' without declaring it as global 5 print(x) 6 UnboundLocalError: local variable 'x' referenced before assignment
x = 5 def modify_global(): global x # Declare x as global x += 1 # Modify the global x print(x) modify_global()Output
6
How to Fix UnboundLocalError: local variable referenced before assignment error.
Initialize Variables Before Use
def example_function(): result = None # Initialize before use try: result = some_operation() except Exception as e: print("An error occurred:", e) print(result) # Safe to access result now
Use the 'global' Keyword
If we want to modify a global variable within a function, we first need to declare that variable as global as shown in below example.
In the below example I defined x as global in the “modify_global” function which helps me to modify the value of x.
x = 5 def modify_global(): global x # Declare 'x' as global x += 1 print(x) modify_global() # output : 6
Use the 'nonlocal' Keyword
A variable in the outer function can not be directly accessed for modification inside a nested function but with help of nonlocal, we can tell Python that you want to modify the variable from the outer function’s scope.
I have used nonlocal x, to modify x in “inner_function()”
def outer_function(): x = 10 def inner_function(): nonlocal x # Declare 'x' as nonlocal x += 5 inner_function() print(x) # Outputs: 15 outer_function()
Avoid shadowing variables
We should always prevent confusion between local and global variable by using a different variable names.
In the below example I have used index and local_index as global variable and local variable to avoid confusion.
index = 0 def foo(): if index == 0: print("ZERO") local_index = 1 # Use a different name for local variable foo() # Outputs: ZERO
Conclusion :
In the blog we have discussed common causes for unboundlocalerror local variables referenced before assignment and how to solve this error.
Keep in kind these points to avoid errors :
- Use different names for local and global variables
- When You want to modify a global variable inside a function, define the variable as global before accessing it.
- Always Initialize the variable before accessing it.
- If you want to modify a variable in the outer function of a nested function, make use of nonlocal.
You can refer our other blogs on how to convert a dataframe to excel sheet and how to solve typeerror: unhashable type: ‘numpy.ndarray’ error in Python.
Pingback: Notimplementederror: cannot copy out of meta tensor; no data!