The nonlocal keyword lets you change a variable in an outer function from inside a nested function. It helps when you want to keep track of changes without using global variables.
0
0
Nonlocal keyword in Python
Introduction
When you have a function inside another function and want to update a variable from the outer function.
When you want to remember a value that changes each time the inner function runs.
When you want to avoid using global variables but still share data between nested functions.
Syntax
Python
def outer_function(): variable = None def inner_function(): nonlocal variable variable = 'new_value' inner_function()
You must declare nonlocal before changing the variable inside the inner function.
The variable must exist in the nearest outer function scope, not global or local to inner function.
Examples
This example shows how
nonlocal lets the inner function update count from the outer function.Python
def counter(): count = 0 def increment(): nonlocal count count += 1 return count return increment count_up = counter() print(count_up()) # 1 print(count_up()) # 2
The inner function changes the
message variable from the outer function using nonlocal.Python
def greet(): message = 'Hello' def change_message(): nonlocal message message = 'Hi' change_message() print(message) greet() # Output: Hi
Sample Program
This program uses nonlocal to increase factor each time the inner function runs, changing the multiplication result.
Python
def make_multiplier(): factor = 2 def multiply(number): nonlocal factor factor += 1 return number * factor return multiply multiplier = make_multiplier() print(multiplier(5)) # First call print(multiplier(5)) # Second call
OutputSuccess
Important Notes
If you forget nonlocal, Python treats the variable as local and you get an error if you try to assign it.
nonlocal only works with variables in the nearest outer function, not global variables.
Summary
nonlocal lets inner functions change variables from outer functions.
It helps keep track of changing data without using global variables.
Always declare nonlocal before assigning to the variable inside the inner function.