Definitions - Nonlocal Variables in Python 2026
A nonlocal variable is a variable that belongs to the enclosing (outer) function’s scope and is accessed or modified from within a nested (inner) function. The nonlocal keyword is used to explicitly tell Python that we want to refer to the variable in the nearest enclosing scope rather than creating a new local variable.
TL;DR — Key Definitions 2026
- Nonlocal Variable: A variable defined in an enclosing function that can be read or modified by a nested function
- nonlocal Keyword: Declares that a name refers to a variable in the nearest enclosing scope (not global, not local)
- Enclosing Scope: The scope of the function that contains the nested function
- Closure: A nested function that "remembers" its nonlocal variables even after the outer function has returned
1. Clear Definition with Example
def outer():
x = 10 # This is a nonlocal variable for the inner function
def inner():
nonlocal x # Explicitly refer to the variable in outer scope
x += 5 # Modifies the nonlocal variable
print("Inside inner:", x)
inner()
print("Inside outer after inner:", x)
outer()
# Output:
# Inside inner: 15
# Inside outer after inner: 15
2. Without nonlocal (Common Mistake)
def outer():
x = 10
def inner():
x = 20 # This creates a NEW local variable!
print("Inside inner:", x)
inner()
print("Inside outer:", x) # Still 10 - unchanged
outer()
3. Best Practices for Nonlocal Variables (2026)
- Always use the
nonlocalkeyword when you intend to modify a variable from the enclosing scope - Keep the number of nonlocal variables small for readability
- Document the purpose of each nonlocal variable clearly
- When state becomes complex, prefer a class over many nonlocal variables
- Use type hints on both outer and inner functions
Conclusion
Understanding nonlocal variables is essential for working effectively with nested functions and closures in Python. The nonlocal keyword clearly signals your intention to modify a variable from the enclosing scope rather than creating a local one. In 2026, proper use of nonlocal variables leads to cleaner, more predictable, and maintainable code.
Next steps:
- Review your nested functions and ensure every reassignment of enclosing variables uses the
nonlocalkeyword - Related articles: Writing Functions in Python 2026 • The nonlocal Keyword in Python 2026 • Nested Functions in Python 2026