gotchapythonModerate
UnboundLocalError when assigning to variable that exists in outer scope
Viewed 0 times
UnboundLocalErrorvariable scopeglobalnonlocalreferenced before assignment
Error Messages
Problem
Referencing a variable before assigning it in a function raises UnboundLocalError, even if the variable exists in the outer/global scope. Python sees the assignment later in the function and treats it as local for the entire function body.
Solution
Use 'global' or 'nonlocal' keywords:
count = 0
# For global variables
def increment():
global count
count += 1
# For enclosing function variables
def outer():
count = 0
def inner():
nonlocal count
count += 1
inner()
# Better: avoid mutation, return new values
def increment(count):
return count + 1
count = 0
# For global variables
def increment():
global count
count += 1
# For enclosing function variables
def outer():
count = 0
def inner():
nonlocal count
count += 1
inner()
# Better: avoid mutation, return new values
def increment(count):
return count + 1
Why
Python determines variable scope at compile time, not runtime. If a variable is assigned anywhere in a function, it's treated as local for the entire function — even lines before the assignment. This is different from JavaScript's hoisting.
Gotchas
- global and nonlocal must appear before any use of the variable in the function
- Augmented assignment (+=) counts as an assignment
- This is determined at compile time — even unreachable assignments affect scope
Code Snippets
UnboundLocalError scope fix
x = 10
def broken():
print(x) # UnboundLocalError!
x = 20 # This makes x local for the ENTIRE function
def fixed():
global x
print(x) # 10
x = 20Context
When trying to modify an outer scope variable inside a function
Revisions (0)
No revisions yet.