nonlocalEasy Examples

Declares a variable inside a nested function as belonging to the enclosing scope

Modify enclosing scope variables

Using nonlocal to change variables in an outer function.

python
def outer():
    message = "hello"

    def inner():
        nonlocal message
        message = "goodbye"

    print(f"Before: {message}")
    inner()
    print(f"After: {message}")

outer()

# Practical: counter closure
def make_counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

counter = make_counter()
print(counter())
print(counter())
print(counter())
Expected Output
Before: hello
After: goodbye
1
2
3

nonlocal lets an inner function modify a variable from its enclosing function's scope, not the global scope.

Want to try these examples interactively?

Open Easy Playground