You can fix the UnboundLocalError
in Python by either assigning a value to the local variable before you use it or by using the global
keyword if you are trying to modify a global variable within a function.
Understanding the UnboundLocalError
The UnboundLocalError: local variable referenced before assignment
is a common error in Python. It occurs when a function attempts to use a variable in its local scope, but no value has been assigned to that variable within that function's scope before it is accessed.
Python's behavior for variable scope within functions can sometimes be counter-intuitive. If you assign a value to a variable inside a function, Python automatically considers that variable local to the function. If you then try to access a variable with the same name before that assignment happens within the function, Python assumes you are referring to the local variable (which hasn't been assigned yet) rather than a global variable with the same name (if one exists). This leads to the UnboundLocalError
.
Resolving UnboundLocalError
Based on best practices and the provided information, there are two primary methods to resolve this error:
1. Initialize the Variable Before Use
This is the recommended approach when the variable is genuinely intended to be local to the function. Ensure that every possible execution path through your function assigns an initial value to the variable before you attempt to read from it.
-
Why it works: By assigning an initial value (like
None
, an empty string""
,0
, or an empty list[]
), you create and assign the local variable in the function's scope before any attempt is made to read it. -
Example:
def calculate_discount(price, is_member): # Problematic: discount_rate might not be assigned # if is_member is False and you try to use it later # Initialize the variable before conditional assignment discount_rate = 0.0 if is_member: discount_rate = 0.10 # Assigns value if member # Now discount_rate is always assigned before being used final_price = price * (1 - discount_rate) print(f"Final price: {final_price}") calculate_discount(100, True) calculate_discount(100, False) # Works correctly even without the if condition met
2. Use the global
Keyword
Use the global
keyword when you intend to modify a variable that is defined outside the function (a global variable) from within the function. This keyword tells Python not to create a new local variable but to refer to the existing global one.
-
Why it works: The
global
declaration tells Python that when you assign a value to this variable name inside the function, you want to modify the global variable with that name, not create a new local one. Consequently, any subsequent use of that variable name within the function also refers to the global variable. -
Example:
counter = 0 # Global variable def increment_counter(): # Problematic: trying to read counter before assigning to # what Python thinks is a new local counter # print(counter) # This would cause UnboundLocalError if uncommented here # Use global keyword to indicate we mean the global variable global counter # Now we are reading and modifying the global counter counter = counter + 1 print(f"Counter inside function: {counter}") print(f"Counter before: {counter}") # Output: Counter before: 0 increment_counter() # Output: Counter inside function: 1 increment_counter() # Output: Counter inside function: 2 print(f"Counter after: {counter}") # Output: Counter after: 2
Without
global counter
, the linecounter = counter + 1
inside the function would attempt to read a local variable namedcounter
(from the right side of the assignment) before it has been assigned a value within the function, causing the error.
Choosing the Right Solution
The method you choose depends entirely on whether the variable is meant to be local to the function or if you intend to modify a global variable.
Situation | Recommended Fix |
---|---|
Variable should exist only within the function. | Initialize the variable before its first use within the function. |
Variable is defined globally, and you want to change its value inside the function. | Use the global variable_name statement at the beginning of the function before using the variable. |
By correctly initializing local variables or explicitly declaring global variables with the global
keyword, you can avoid the UnboundLocalError
and ensure your variables are properly scoped and assigned before they are used.