Attaching Nonlocal Variables to Nested Functions in Python 2026 – Best Practices
Attaching nonlocal variables to nested functions (creating closures) is a powerful technique in Python. It allows inner functions to "remember" and modify variables from their enclosing scope even after the outer function has finished executing.
TL;DR — Key Takeaways 2026
- Use
nonlocalto modify variables from the enclosing scope - The inner function "closes over" the nonlocal variables, creating a closure
- This pattern is widely used for factory functions, decorators, and stateful callbacks
- Keep closures simple — for complex state, prefer classes
1. Basic Closure with nonlocal
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
# Each call creates its own independent closure
c1 = make_counter()
c2 = make_counter()
print(c1()) # 1
print(c1()) # 2
print(c2()) # 1
print(c1()) # 3
2. Advanced Example – Configurable Factory
def make_formatter(prefix: str, suffix: str = ""):
"""Returns a customized formatting function."""
def formatter(text: str) -> str:
nonlocal prefix, suffix # Allows modification if needed
return f"{prefix}{text}{suffix}"
return formatter
# Create specialized formatters
error_msg = make_formatter("[ERROR] ", "!")
warning_msg = make_formatter("[WARNING] ")
print(error_msg("File not found")) # [ERROR] File not found!
print(warning_msg("Low disk space")) # [WARNING] Low disk space
3. Best Practices in 2026
- Use
nonlocalexplicitly when modifying enclosing variables - Keep the outer function focused and the inner function small
- Document what variables the closure depends on
- Use type hints with
Callablefor the returned function - When state becomes complex, switch to a class instead of a closure
Conclusion
Attaching nonlocal variables to nested functions is a clean and efficient way to create stateful, reusable functions in Python. In 2026, this closure pattern remains one of the most elegant ways to implement factory functions, decorators, and lightweight state management.
Next steps:
- Identify repeated logic in your code and replace it with closure-based factories
- Related articles: Writing Functions in Python 2026 • Defining a Function Inside Another Function in Python 2026 • The nonlocal Keyword in Python 2026