In this lesson, you will learn how to modify variables defined in an enclosing function from within a nested function using the nonlocal keyword.
The Scope Challenge
When you define a function inside another function, the inner function can read variables from the outer function’s scope. However, by default, if you try to assign a new value to an outer variable from inside the inner function, Python assumes you are creating a brand-new local variable. This often leads to errors or unexpected behavior when you are trying to update an existing counter or flag.
Introducing nonlocal
The nonlocal keyword tells Python that a specific variable name does not belong to the local scope of the inner function, nor is it a global variable. Instead, it refers to a variable in the nearest enclosing scope.
Consider this counter example:
def outer_counter():
count = 0 # Enclosing scope variable
def increment():
nonlocal count # Declaring we want to modify the outer 'count'
count += 1
return count
return increment
my_counter = outer_counter()
print(my_counter()) # Output: 1
print(my_counter()) # Output: 2
In the code above, without nonlocal count, Python would raise an UnboundLocalError because it would see count += 1 and assume count is local to increment, but it hasn't been defined there yet. By using nonlocal, we explicitly allow the nested function to reach out and update the state held by the outer function.
When to Use It
Use nonlocal when you are creating closures—functions that "remember" and modify their own state across multiple calls. It is a powerful way to encapsulate data within a function without relying on global variables, which helps keep your code modular and organized.
Key Takeaway: The nonlocal keyword allows nested functions to modify variables in an enclosing scope, enabling you to maintain persistent state within encapsulated function structures.