Closures

Concepts covered: Scope

A nested function can also be the return value. When make_range_check below returns check, its parameters low and high would normally disappear with the call, yet check still reads them, so Python keeps them alive and attaches them to the returned function. A function packaged with the enclosing variables it uses is a closure. A function that builds and returns closures is a function factory.

from typing import Callable

def make_range_check(low: int, high: int) -> Callable[[int], bool]:
    def check(value: int) -> bool:
        return low <= value <= high
    return check

valid_age = make_range_check(0, 120)
valid_pct = make_range_check(0, 100)

print(valid_age(110), valid_pct(110))
print(list(filter(valid_pct, [-5, 40, 100, 130])))

Output:

True False
[40, 100]

valid_age and valid_pct run identical code and answer differently, because each call to make_range_check creates a new low and high, and the returned check carries that call's pair. The hint Callable[[int], bool] says the factory returns a function that takes an int and returns a bool.

Where captured variables live

Python stores each captured variable in a cell, a small container that the outer function and the closure share. A function lists the names it captures in __code__.co_freevars and holds the cells themselves in __closure__, a tuple you can index.

def make_prefixer(prefix):
    def add(name):
        return prefix + name
    return add

staging = make_prefixer("stg_")
print(staging("orders"))
print(staging.__code__.co_freevars)
print(staging.__closure__[0].cell_contents)

Output:

stg_orders
('prefix',)
stg_

A cell is the variable's storage, so the closure reads whatever the cell holds at the moment it runs. If the outer function rebinds prefix before returning, the closure sees the new value, and the last section of this lesson shows that behaviour turning into a bug.

Keeping state with nonlocal

In the make_counter factory below, the inner function increment runs count += 1 on the factory's own count, which starts at 0. Assigning to a captured name follows the rule from nested functions: the name becomes local to increment. Without a declaration, count += 1 would try to read a local that has no value yet, and Python raises UnboundLocalError. Declaring nonlocalcount at the top of increment tells Python that count belongs to the enclosing function, so the assignment updates the shared cell instead.

Every call to make_counter creates a fresh cell, so 2 counters keep separate counts:

def make_counter(name):
    count = 0

    def increment():
        nonlocal count
        count += 1
        print(f"{name}: {count}")
        return count

    return increment

orders = make_counter("orders")
users = make_counter("users")
orders()
orders()
users()
orders()
orders: 1
orders: 2
users: 1
orders: 3
Closure factory
  • Wraps new logic around the captured values
  • Can update its state between calls with nonlocal
  • Lists captured names in __code__.co_freevars
partial
  • Presets arguments of a function that already exists
  • Keeps its preset values fixed for its whole life
  • Lists preset values in .args and .keywords

What does the last line print?

def make_tracker():
    total = 0
    def add(n):
        nonlocal total
        total += n
        return total
    return add

a = make_tracker()
b = make_tracker()
a(5)
b(2)
print(a(10), b(1))

Leave out the nonlocal line and the factory itself runs without complaint: the failure waits for the first call to the returned function. Python settles each name's scope when it reads the inner def, before any line of it runs, so count += 1 makes count local to the whole body. The traceback's last line reads UnboundLocalError: local variable 'count' referenced before assignment, and the frame above it names the inner function and its count += 1 line. An assignment in an inner function to a name the outer function defines is the signal to add nonlocal.

About this lesson

This section is part of the Functional Programming: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.