nonlocalIntermediate Examples

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

nonlocal vs global

Understanding the difference between nonlocal and global.

python
x = "global"

def outer():
    x = "outer"

    def use_nonlocal():
        nonlocal x
        x = "modified by nonlocal"

    def use_global():
        global x
        x = "modified by global"

    use_nonlocal()
    print(f"After nonlocal: outer x = {x}")

    use_global()
    print(f"After global: outer x = {x}")

outer()
print(f"Module x = {x}")
Expected Output
After nonlocal: outer x = modified by nonlocal
After global: outer x = modified by nonlocal
Module x = modified by global

nonlocal targets the nearest enclosing function scope. global targets the module scope. They affect different variables.

Closures with state

Building stateful closures with nonlocal.

python
def make_accumulator(initial=0):
    total = initial
    def add(amount):
        nonlocal total
        total += amount
        return total
    def reset():
        nonlocal total
        total = initial
    def get():
        return total
    return add, reset, get

add, reset, get = make_accumulator(100)
print(add(10))
print(add(20))
print(get())
reset()
print(get())
Expected Output
110
130
130
100

nonlocal enables multiple inner functions to share and modify the same enclosing variable, creating a lightweight alternative to classes.

Want to try these examples interactively?

Open Intermediate Playground