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
Unused local variable in Python
A variable defined inside a function block or a looping block loses its scope outside that block is called ad local variable to that block. A local variable cannot be accessed outside the block it is defined. Example: Python3 # simple display function def func(num): # local variable a = num print(
4 min read
Unused variable in for loop in Python
Prerequisite: Python For loops The for loop has a loop variable that controls the iteration. Not all the loops utilize the loop variable inside the process carried out in the loop. Example: Python3 # i,j - loop variable # loop-1 print("Using the loop variable inside :") # used loop variabl
3 min read
Access environment variable values in Python
An environment variable is a variable that is created by the Operating System. Environment variables are created in the form of Key-Value pairs. To Access environment variables in Python's we can use the OS module which provides a property called environ that contains environment variables in key-va
3 min read
Assign Function to a Variable in Python
In Python, functions are first-class objects, meaning they can be assigned to variables, passed as arguments and returned from other functions. Assigning a function to a variable enables function calls using the variable name, enhancing reusability.Example:Python# defining a function def a(): print(
3 min read
Global and Local Variables in Python
Python Global variables are those which are not defined inside any function and have a global scope whereas Python local variables are those which are defined inside a function and their scope is limited to that function only. In other words, we can say that local variables are accessible only insid
7 min read
Pass by reference vs value in Python
Developers jumping into Python programming from other languages like C++ and Java are often confused by the process of passing arguments in Python. The object-centric data model and its treatment of assignment are the causes of the confusion at the fundamental level.In the article, we will be discus
7 min read
Get Variable Name As String In Python
In Python, getting the name of a variable as a string is not as straightforward as it may seem, as Python itself does not provide a built-in function for this purpose. However, several clever techniques and workarounds can be used to achieve this. In this article, we will explore some simple methods
3 min read
Undefined Variable Nameerror In Python
Encountering the "NameError: name 'var' is not defined" is a common experience for Python users. In Python, variable declaration is a straightforward process of assigning a value. This error arises when attempting to access a non-existent variable or one not defined in the program. Surprisingly, it
5 min read
Difference between Local Variable and Global variable
Local variables are declared within a specific block of code, such as a function or method, and have limited scope and lifetime, existing only within that block. Global variables, on the other hand, are declared outside of any function and can be accessed from any part of the program, persisting thr
2 min read
__name__ (A Special variable) in Python
Since there is no main() function in Python, when the command to run a python program is given to the interpreter, the code that is at level 0 indentation is to be executed. However, before doing that, it will define a few special variables. __name__ is one such special variable. If the source file
2 min read