How to Fix SyntaxError: no binding for nonlocal in Python
In this tutorial, you'll learn about How to Fix SyntaxError: no binding for nonlocal in Python. We cover key concepts, practical examples, and best practices.
Python raises SyntaxError: no binding for nonlocal when the nonlocal keyword references a variable that does not exist in any enclosing (non-global) function scope.
The Wrong Way
def outer():
x = 10
def inner():
nonlocal x
x = 20
inner()
print(x)
outer()
Wait -- this works fine. The error happens when there is no enclosing scope for the variable:
def outer():
def inner():
nonlocal x # no 'x' in outer()
x = 20
inner()
outer()
This produces:
File "script.py", line 3
nonlocal x
^
SyntaxError: no binding for nonlocal 'x' found
The Right Way
Define the variable in the enclosing function before using it with nonlocal:
def outer():
x = 10 # define x in enclosing scope
def inner():
nonlocal x
x = 20
inner()
print(x)
outer()
Output:
20
Step-by-Step Fix
1. Verify the variable exists in an enclosing scope
def outer():
def middle():
def inner():
nonlocal x # x must exist in outer or middle
x = 5
inner()
middle()
outer() # SyntaxError
Fix by defining x in outer or middle.
2. Use the correct nesting level
def outer():
x = 1
def middle():
x = 2 # this creates a new local x
def inner():
nonlocal x # refers to middle's x, not outer's x
x = 3
inner()
print(x) # 3
middle()
print(x) # 1
outer()
3. Use a mutable container for deep nesting
def outer():
state = {"x": 1}
def middle():
def inner():
state["x"] = 3 # no nonlocal needed
inner()
middle()
print(state["x"])
outer()
Output:
3
4. Restructure to avoid deep nesting
Refactor nested functions into separate named functions.
Prevention Tips
- Define all nonlocal variables in the immediate enclosing scope.
- Use mutable containers (
dict,list) to avoid nonlocal altogether. - Restructure deeply nested functions to reduce complexity.
- Use classes instead of nested functions with shared state.
- Test the enclosing scope hierarchy before using nonlocal.
Common Mistakes with nonlocal error
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro