Skip to content

How to Fix SyntaxError: no binding for nonlocal in Python

DodaTech Updated 2026-06-24 3 min read

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

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. 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

### What is the difference between nonlocal and global?

nonlocal looks for a variable in the nearest enclosing function scope (excluding global). global looks at the module-level scope. If a variable is at module level, use global, not nonlocal.

Can nonlocal work across multiple nesting levels?

Yes. Python searches up through enclosing scopes until it finds the variable. The variable must exist in at least one enclosing scope, not necessarily the immediate one.

Why does nonlocal only work with function scopes?

nonlocal is specifically designed for closures -- nested functions that reference variables from enclosing functions. Class bodies and module scopes use global instead.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro