Keywords and Control Flow

nonlocal — Enclosing function binding

Rebind an existing name in an enclosing function scope rather than creating a local binding. When multiple enclosing functions bind the name, the nearest applicable binding is chosen. The module namespace is not a nonlocal scope. The name must already be bound by an enclosing function block, and use or assignment before the declaration in the same block is invalid. The directive is useful in stateful closures; modifying an already referenced mutable object does not itself require nonlocal.

Formal Syntax & Structure

python syntaxpython
nonlocal name[, another_name ...]

Working Example

Example Snippetpython
def counter():    value = 0    def advance():        nonlocal value        value += 1        return value    return advance
step = counter()print(step(), step())print(counter()())
Python Reference