In this lesson, you will learn how to create "private" storage for your functions by using closures to maintain state across multiple calls.
The Problem with State
Usually, when a function finishes executing, all its local variables disappear. If you want to keep track of something—like a counter or a user's score—without relying on messy global variables, you need a way to make that data "stick around" even after the function exits.
How Closures Help
A closure is a function that remembers the environment in which it was created. By defining a function inside another function, the inner function gains access to the variables of the outer function. If we return that inner function, it carries the outer function's local variables with it, effectively "locking" them away from the rest of your program.
To modify these captured variables, we use the nonlocal keyword, which tells Python that we want to update the variable in the enclosing scope rather than creating a new local one.
A Concrete Example
Consider a simple counter that keeps track of how many times it has been called:
def make_counter():
count = 0 # This variable is captured by the closure
def increment():
nonlocal count
count += 1
return count
return increment
# Create a specific counter instance
my_counter = make_counter()
print(my_counter()) # Output: 1
print(my_counter()) # Output: 2
In this code, make_counter finishes running immediately after it returns increment. However, because increment is a closure, it keeps a reference to count. Every time you call my_counter(), it updates that same count variable, maintaining its state throughout the life of the my_counter object. This pattern is powerful because it allows you to create multiple independent counters, each with its own private, persistent state, without using a single global variable.
Key Takeaway: Closures allow you to wrap data and behavior together, enabling functions to maintain private state between calls by capturing variables from an enclosing scope.