In Python, the error message:
NameError: cannot access local variable 'x' before assignment
occurs when you try to reference a local variable before assigning it a value inside a function.
This error is caused by Python’s variable scope rules, where it assumes that any variable assigned inside a function is local to that function, unless explicitly declared otherwise.
1. What Does the Error Mean?
When a variable is assigned inside a function, Python treats it as a local variable unless we use the global
or nonlocal
keyword. If we try to access the variable before assigning it a value, Python throws this error.
Example of the Error:
def my_function():
print(x) # Trying to access 'x' before assigning it
x = 10
my_function()
Error Output:
UnboundLocalError: cannot access local variable 'x' before assignment
Here, Python sees x = 10
inside the function and assumes x
is a local variable. Since print(x)
comes before x = 10
, Python tries to access x
before it’s assigned, causing an error.
2. Causes and Solutions
Cause 1: Using a Local Variable Before Assigning a Value
If you try to use a local variable before assigning it a value inside a function, Python will throw this error.
Example:
def my_function():
print(x) # Using 'x' before assignment
x = 5
my_function()
Error Output:
UnboundLocalError: cannot access local variable 'x' before assignment
Solution:
Assign the variable before using it.
def my_function():
x = 5 # Assign first
print(x) # Now, it works fine
my_function()
Cause 2: Confusion Between Global and Local Scope
If a variable with the same name exists globally, but we assign a value to it inside a function, Python treats it as local, ignoring the global variable.
Example:
x = 10 # Global variable
def my_function():
print(x) # Python assumes 'x' is local but finds no assignment before this
x = 20
my_function()
Error Output:
UnboundLocalError: cannot access local variable 'x' before assignment
Python assumes that x
inside my_function()
is local, but since print(x)
appears before x = 20
, it raises an error.
Solution 1: Use the global
Keyword
If you want to modify the global variable inside the function, use global
:
x = 10 # Global variable
def my_function():
global x # Now, 'x' refers to the global variable
print(x) # No error
x = 20 # Modifying global 'x'
my_function()
print(x) # Output: 20
Solution 2: Use a Local Variable Correctly
If x
should be local, define it before using it:
pythonCopyEditdef my_function():
x = 20 # Assign first
print(x) # No error
my_function()
Cause 3: Issue with nonlocal
in Nested Functions
If you’re using nested functions, assigning a value to a variable in an inner function without declaring it nonlocal
can lead to this error.
Example:
def outer():
x = 10 # 'x' is in the outer function
def inner():
print(x) # Trying to access 'x' before assignment
x = 20 # Python treats this as a new local variable
inner()
outer()
Error Output:
UnboundLocalError: cannot access local variable 'x' before assignment
Python sees x = 20
inside inner()
, treats x
as local, and complains because print(x)
appears before assignment.
Solution: Use nonlocal
To modify x
inside inner()
, use nonlocal
:
def outer():
x = 10 # 'x' is in the outer function
def inner():
nonlocal x # Refers to 'x' in outer()
print(x) # No error
x = 20 # Modifies 'x' from outer()
inner()
print(x) # Output: 20
outer()
Cause 4: Using Variables from List Comprehensions Improperly
Python’s list comprehensions create their own scope, which can cause UnboundLocalError
when used incorrectly.
Example:
x = 10
nums = [x for x in range(5)] # 'x' inside comprehension is local
print(x) # Trying to access 'x' from the global scope
Error Output:
UnboundLocalError: cannot access local variable 'x' before assignment
Python treats x
inside [x for x in range(5)]
as a new local variable, overriding the global x
.
Solution: Use a Different Variable Name
x = 10
nums = [num for num in range(5)] # Use a different name
print(x) # No error, Output: 10
3. Best Practices to Avoid This Error
To prevent UnboundLocalError: cannot access local variable before assignment
, follow these best practices:
Define Variables Before Using Them
Always assign a value to a variable before using it.
x = 5
print(x) # No error
Use global
or nonlocal
When Needed
If modifying a global variable inside a function, use global
:
x = 100
def modify_x():
global x
x += 50
modify_x()
print(x) # Output: 150
If modifying a variable from an outer function inside a nested function, use nonlocal
:
def outer():
x = 10
def inner():
nonlocal x
x += 5
inner()
print(x) # Output: 15
outer()
Avoid Variable Name Conflicts
Use unique variable names in loops and list comprehensions to avoid scope issues.
x = 10
nums = [num for num in range(5)] # No conflict
print(x) # Output: 10
Handle Errors Gracefully
Use a try-except
block to handle missing variables.
try:
print(undeclared_var)
except NameError:
print("Variable is not defined!")