What does the Python nonlocal statement do (in Python 3.0 and later)?

Technology CommunityCategory: PythonWhat does the Python nonlocal statement do (in Python 3.0 and later)?
VietMX Staff asked 3 years ago

In short, it lets you assign values to a variable in an outer (but non-global) scope.

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.

For example the counter generator can be rewritten to use this so that it looks more like the idioms of languages with closures.

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