UnboundLocalError Local variable Referenced Before Assignment in Python
Last Updated :
01 Mar, 2024
Handling errors is an integral part of writing robust and reliable Python code. One common stumbling block that developers often encounter is the "UnboundLocalError" raised within a try-except block. This error can be perplexing for those unfamiliar with its nuances but fear not – in this article, we will delve into the intricacies of the UnboundLocalError and provide a comprehensive guide on how to effectively use try-except statements to resolve it.
What is UnboundLocalError Local variable Referenced Before Assignment in Python?
The UnboundLocalError occurs when a local variable is referenced before it has been assigned a value within a function or method. This error typically surfaces when utilizing try-except blocks to handle exceptions, creating a puzzle for developers trying to comprehend its origins and find a solution.
Syntax:
UnboundLocalError: local variable 'result' referenced before assignment
Why does UnboundLocalError: Local variable Referenced Before Assignment Occur?
below, are the reasons of occurring "Unboundlocalerror: Try Except Statements" in Python:
- Variable Assignment Inside Try Block
- Reassigning a Global Variable Inside Except Block
- Accessing a Variable Defined Inside an If Block
Variable Assignment Inside Try Block
In the below code, example_function
attempts to execute some_operation
within a try-except block. If an exception occurs, it prints an error message. However, if no exception occurs, it prints the value of the variable result
outside the try block, leading to an UnboundLocalError since result
might not be defined if an exception was caught.
Python3
def example_function():
try:
result = some_operation()
except Exception as e:
print("An error occurred:", e)
print(result)
# Calling the function
example_function()
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 9, in <module>
example_function()
File "Solution.py", line 6, in example_function
print(result)
UnboundLocalError: local variable 'result' referenced before assignment
Reassigning a Global Variable Inside Except Block
In below code , modify_global
function attempts to increment the global variable global_var
within a try block, but it raises an UnboundLocalError. This error occurs because the function treats global_var
as a local variable due to the assignment operation within the try block.
Python3
global_var = 42
def modify_global():
try:
global_var += 1
except Exception as e:
print("An error occurred:", e)
print(global_var)
# Calling the function
modify_global()
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 11, in <module>
modify_global()
File "Solution.py", line 8, in modify_global
print(global_var)
UnboundLocalError: local variable 'global_var' referenced before assignment
Solution for UnboundLocalError Local variable Referenced Before Assignment
Below, are the approaches to solve "Unboundlocalerror: Try Except Statements".
- Initialize Variables Outside the Try Block
- Avoid Reassignment of Global Variables
Initialize Variables Outside the Try Block
In modification to the example_function
is correct. Initializing the variable result
before the try block ensures that it exists even if an exception occurs within the try block. This helps prevent UnboundLocalError when trying to access result
in the print statement outside the try block.
Python3
def example_function():
result = None # Initialize the variable before the try block
try:
result = some_operation()
except Exception as e:
print("An error occurred:", e)
print(result)
Avoid Reassignment of Global Variables
Below, code calculates a new value (local_var
) based on the global variable and then prints both the local and global variables separately. It demonstrates that the global variable is accessed directly without being reassigned within the function.
Python3
global_var = 42
def modify_global():
try:
local_var = global_var + 1
except Exception as e:
print("An error occurred:", e)
print(global_var) # Access the global variable directly
Conclusion
In conclusion , To fix "UnboundLocalError" related to try-except statements, ensure that variables used within the try block are initialized before the try block starts. This can be achieved by declaring the variables with default values or assigning them None outside the try block. Additionally, when modifying global variables within a try block, use the `global` keyword to explicitly declare them.
Similar Reads
How to Fix - UnboundLocalError: Local variable Referenced Before Assignment in Python
Developers often encounter the UnboundLocalError Local Variable Referenced Before Assignment error in Python. In this article, we will see what is local variable referenced before assignment error in Python and how to fix it by using different approaches. What is UnboundLocalError: Local variable Re
3 min read
Python | Accessing variable value from code scope
Sometimes, we just need to access a variable other than the usual way of accessing by it's name. There are many method by which a variable can be accessed from the code scope. These are by default dictionaries that are created and which keep the variable values as dictionary key-value pair. Let's ta
3 min read
Variables under the hood in Python
In simple terms, variables are names attached to particular objects in Python. To create a variable, you just need to assign a value and then start using it. The assignment is done with a single equals sign (=): C/C++ Code # Variable named age age = 20 print(age) # Variable named id_number id_no = 4
3 min read
Assign Multiple Variables with List Values - Python
We are given a list and our task is to assign its elements to multiple variables. For example, if we have a list a = [1, 2, 3], we can assign the elements of the list to variables x, y, z such that x = 1, y = 2, and z = 3. Below, we will explore different methods to assign list values to variables.
3 min read
Different Forms of Assignment Statements in Python
We use Python assignment statements to assign objects to names. The target of an assignment statement is written on the left side of the equal sign (=), and the object on the right can be an arbitrary expression that computes an object. There are some important properties of assignment in Python :-
3 min read
Insert a Variable into a String - Python
The goal here is to insert a variable into a string in Python. For example, if we have a variable containing the word "Hello" and another containing "World", we want to combine them into a single string like "Hello World". Let's explore the different methods to insert variables into strings effectiv
2 min read
Python program to find number of local variables in a function
Given a Python program, task is to find the number of local variables present in a function. Examples: Input : a = 1 b = 2.1 str = 'GeeksForGeeks' Output : 3 We can use the co_nlocals() function which returns the number of local variables used by the function to get the desired result. Code #1: # Im
1 min read
Python Program to Find and Print Address of Variable
In this article, we are going to see how to find and print the address of the Python variable. It can be done in these ways: Using id() functionUsing addressof() functionUsing hex() functionMethod 1: Find and Print Address of Variable using id()We can get an address using id() function, id() functio
2 min read
Accessing Python Function Variable Outside the Function
In Python, function variables have local scope and cannot be accessed directly from outside. However, their values can still be retrieved indirectly. For example, if a function defines var = 42, it remains inaccessible externally unless retrieved indirectly. Returning the VariableThe most efficient
4 min read
Python | Using variable outside and inside the class and method
In Python, we can define the variable outside the class, inside the class, and even inside the methods. Let's see, how to use and access these variables throughout the program. Variable defined outside the class: The variables that are defined outside the class can be accessed by any class or any me
3 min read