nonlocal

A statement that lets an inner function rebind a variable of its enclosing function.

In more detail

Without nonlocal, any assignment to a name inside a function, including +=, makes that name local, so reading it first raises UnboundLocalError. nonlocal count tells Python to use the enclosing function's count instead. It is the usual way for a closure to keep changing state between calls.

Example

def make_counter():
    count = 0
    def tick():
        nonlocal count
        count += 1
        return count
    return tick

Related terms

Taught in

References

Certification courses