The nonlocal
keyword in Python is used inside nested functions to indicate that a variable is not local to the current function but belongs to an enclosing (non-global) scope. It allows the modification of variables defined in the nearest enclosing function scope.
Example
def outer_function():
count = 0 # Defined in the enclosing scope
def inner_function():
nonlocal count # Modify the variable in the enclosing scope
count += 1
print(f"Count inside inner_function: {count}")
inner_function()
print(f"Count inside outer_function: {count}")
outer_function()
Output:
Count inside inner_function: 1
Count inside outer_function: 1
Syntax
nonlocal variable_name
variable_name
: The name of the variable from the enclosing scope that you want to modify.
Why Use nonlocal?
- Modify Enclosing Scope Variables: Allows a nested function to change variables in the enclosing (but non-global) scope.
- Encapsulation: Useful for managing state or counters within nested functions while keeping them private to the enclosing function.
- Alternative to Globals: Helps avoid using global variables when working with nested functions.
Common Examples
1. Using nonlocal for State Management
def outer():
message = "Hello" # Enclosing scope variable
def inner():
nonlocal message
message = "Hi" # Modify the enclosing variable
print("Inside inner:", message)
inner()
print("Inside outer:", message)
outer()
Output:
Inside inner: Hi
Inside outer: Hi
2. Counter with nonlocal
def counter():
count = 0 # Enclosing scope variable
def increment():
nonlocal count
count += 1
return count
return increment
counter_instance = counter()
print(counter_instance()) # Output: 1
print(counter_instance()) # Output: 2
3. Without nonlocal (For Comparison)
def outer():
x = 5
def inner():
x = 10 # Creates a new local variable, doesn't modify the enclosing one
print("Inner x:", x)
inner()
print("Outer x:", x)
outer()
Output:
Inner x: 10
Outer x: 5