The nonlocal Keyword in Python 2026 – Best Practices for Writing Functions
The nonlocal keyword allows an inner (nested) function to modify a variable from its immediately enclosing (outer) function’s scope. It is the nested-function counterpart to the global keyword and is essential when working with closures and factory functions.
TL;DR — Key Takeaways 2026
nonlocallets inner functions modify variables in the enclosing function scope- It only works inside nested functions (not at module level)
- Commonly used in closures, counters, and stateful inner functions
- Prefer returning values or using classes when possible
1. Basic Usage of nonlocal
def outer():
count = 0
def inner():
nonlocal count # Allows modification of outer's 'count'
count += 1
return count
return inner
counter = outer()
print(counter()) # 1
print(counter()) # 2
print(counter()) # 3
2. Practical Example – Stateful Closure
def make_accumulator(initial: int = 0):
total = initial
def add(value: int) -> int:
nonlocal total
total += value
return total
return add
acc = make_accumulator(100)
print(acc(10)) # 110
print(acc(25)) # 135
print(acc(-5)) # 130
3. Best Practices in 2026
- Use
nonlocalonly when you need to modify enclosing scope variables - Keep the outer function small and focused when using
nonlocal - Document the use of
nonlocalclearly - Consider classes or returning a mutable object when state becomes complex
- Combine with type hints for better readability
Conclusion
The nonlocal keyword is a clean and powerful tool for working with nested functions and closures. In 2026, it is commonly used to create simple stateful functions and factories. However, for more complex state management, classes or returning objects are often preferred for better maintainability.
Next steps:
- Review your nested functions and use
nonlocalwhere you need to modify enclosing variables - Related articles: Writing Functions in Python 2026 • Defining a Function Inside Another Function in Python 2026 • The global Keyword in Python 2026