Course contentsShow
← Python
Lesson 191 of 1,0603. Functions and ModularizationFree lesson

Capturing State with Function Closures

Learners will implement closures to preserve variable state within nested function scopes after the outer function has completed execution.

In this lesson, you will learn how to use closures to "freeze" data inside a function, allowing that function to remember values even after the code that created them has finished running.

The Concept of Persistent State

Usually, when a function finishes executing, its local variables are destroyed and cleared from memory. However, a closure occurs when a nested function references a variable from its outer (enclosing) scope. When you return that nested function, Python keeps the outer variable "alive" in a special container called a __closure__ cell. This effectively bundles the function with a custom "memory."

A Concrete Example

Imagine you want to create a counter that starts at a specific number and increments every time you call it. You don’t want to use a global variable because that could lead to conflicts elsewhere in your program. Instead, you can use a closure:

def make_counter(start_value):
    count = start_value  # This is the state we want to preserve

    def increment():
        nonlocal count  # Allows us to modify the outer scope variable
        count += 1
        return count

    return increment

# Create two independent counters
counter_a = make_counter(0)
counter_b = make_counter(10)

print(counter_a())  # Output: 1
print(counter_a())  # Output: 2
print(counter_b())  # Output: 11

How It Works

  1. When make_counter(0) runs, it defines the variable count.
  2. The nested increment function is defined and "captures" the count variable.
  3. Even though make_counter finishes executing, the returned increment function keeps a reference to that specific count object.
  4. Each time you call counter_a(), it looks into its own private "closure" to find the current value of count, modifies it, and saves it for the next call.

This approach is powerful because it hides the state from the rest of your program, ensuring that counter_a and counter_b stay completely independent, even though they were created by the same code.

Key Takeaway: A closure allows a function to maintain a private, persistent state by capturing and remembering variables from its enclosing scope, even after that scope has finished execution.