Glossary

Nonlocal Statement

The nonlocal statement declares that a variable name inside a nested function refers to the same variable in the nearest enclosing function's scope. Without this declaration, assignment to a name in a nested function creates a new local variable, even if the enclosing function has a variable with the same name. nonlocal was introduced in Python 3.0 (PEP 3104).

nonlocal is most commonly used in closures where the inner function needs to modify (not just read) a captured variable. For example, a counter closure: def make_counter(): count = 0; def increment(): nonlocal count; count += 1; return count; return increment. Without nonlocal, the count += 1 line would create a new local variable and raise UnboundLocalError.

Like global, nonlocal should be used sparingly. Most closure patterns only need to read captured variables, not modify them. When you find yourself using nonlocal, consider whether the pattern would be clearer as a class with instance attributes. Python's explicit nonlocal (like its explicit self) reflects the language's preference for making scope modifications visible and intentional rather than implicit.

Related terms: Scope, LEGB Rule, Closure, Global Statement

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.