Python Functions · Lesson 72 of 149

Python Closures

What you will learn

  • What a closure is: a function that remembers variables from where it was made
  • Function factories: functions that return configured functions
  • State in a closure with nonlocal: counters, accumulators, a bank
  • How to inspect a closure
  • Closures versus classes
  • The loop trap, and how to avoid it

1. A function that remembers

You saw in lesson 11.7 that a function can return another function. Now the important question: when the inner function runs later, where does it get its variables from?

def make_adder(n):
    def add(x):
        return x + n
    return add

add5 = make_adder(5)
add10 = make_adder(10)
print(add5(1), add10(1), add5(100))
6 11 105

After make_adder(5) finishes, its local n should be gone (lesson 11.5). But add5 still works, and still uses 5. The inner function carries its surroundings with it: it keeps the variables it uses from the enclosing function. A function bundled with such remembered variables is called a closure.

Each call to make_adder makes a new add with its own n: add5 remembers 5, and add10 remembers 10, and they do not affect each other.

Quick check: after `double = make_adder(2)`, what is `double(10)`?

12. The function add remembers n = 2 and computes 10 + 2.

2. Looking inside a closure

A closure keeps its remembered variables in cells, which you can look at. This is for understanding and debugging; normal code does not need it:

print(add5.__code__.co_freevars)
print([c.cell_contents for c in add5.__closure__])
print([c.cell_contents for c in add10.__closure__])
print(make_adder.__closure__)
('n',)
[5]
[10]
None
  • co_freevars lists the free variables: names the function uses but does not create.
  • __closure__ holds one cell for each, and cell_contents is the current value.
  • An ordinary function (like make_adder itself) has __closure__ equal to None: it remembers nothing.

3. Function factories

A function that builds and returns configured functions is a factory. The configuration is stored in the closure:

def greeter(greeting):
    return lambda name: f"{greeting}, {name}!"

hello = greeter("Hello")
hi = greeter("Hi")
print(hello("Rina"), hi("Sam"))
print(list(map(hello, ["A", "B"])))

def power_of(exp):
    return lambda base: base ** exp

sq = power_of(2)
cube = power_of(3)
print(sq(5), cube(2))
Hello, Rina! Hi, Sam!
['Hello, A!', 'Hello, B!']
25 8

hello and hi are two functions made from one recipe. A factory is also a good way to adapt a function to an interface that expects one argument, as in map(hello, ...). (functools.partial, lesson 11.7, does a similar job.)

4. State in a closure: nonlocal

A closure can also change its remembered variables, with nonlocal (lesson 11.5). That gives it memory between calls:

def make_counter(start=0):
    count = start

    def tick():
        nonlocal count
        count += 1
        return count

    return tick

a = make_counter()
b = make_counter(100)
print(a(), a(), a())
print(b(), b())
print(a())
1 2 3
101 102
4
  • Each counter has its own count.
  • a carries on from 3 to 4: its state lives in the closure, not in a global variable.
  • Without nonlocal, count += 1 would raise an UnboundLocalError.

An accumulator works the same way:

def make_accumulator():
    total = 0

    def add(x):
        nonlocal total
        total += x
        return total

    return add

acc = make_accumulator()
print(acc(10), acc(5), acc(-3))
10 15 12

Private data: a small bank

A closure can hold several functions that share the same hidden variable. Nobody outside can reach the variable directly, only through the functions you give out:

def bank(balance=0):
    def deposit(x):
        nonlocal balance
        balance += x
        return balance

    def withdraw(x):
        nonlocal balance
        if x > balance:
            raise ValueError("insufficient funds")
        balance -= x
        return balance

    def get():
        return balance

    return deposit, withdraw, get

dep, wd, get = bank(100)
print(dep(50))
print(wd(30))
print(get())
150
120
120
wd(1000)
ValueError: insufficient funds

The variable balance is not a global and not an attribute: the only way to change it is through deposit and withdraw, which enforce the rules. (It is hidden by convention, not locked: a determined programmer can still read dep.__closure__. Python has no truly private data.)

5. A closure or a class?

Both bundle data with behaviour. A class (chapter 13) is the usual tool as the data and functions grow:

class Counter:
    def __init__(self):
        self.n = 0

    def tick(self):
        self.n += 1
        return self.n

c = Counter()
print(c.tick(), c.tick())
1 2
Closure Class
good for one small function that needs a little state several operations on the same data
state hidden in cells visible as attributes
inspect, copy, extend awkward easy
code size short longer, but clearer when it grows

A useful rule: one function with some memory: a closure. Several functions sharing data: a class.

6. Closures share variables, not values

A closure remembers the variable itself, not the value it had at that moment. If the outer variable changes later, the closure sees the change:

def outer():
    items = []
    def add(v):
        items.append(v)
        return len(items)
    return add

add = outer()
print(add(1))
print(add(2))
1
2

The second call sees the item the first call stored. This is the same reason for the loop trap from lesson 11.7: when several functions are made in a loop, they all share one loop variable:

def make_multipliers():
    return [lambda x: x * i for i in range(3)]

print([m(10) for m in make_multipliers()])
[20, 20, 20]

All three look at the same i, which is 2 once the loop is over. There are two ways to give each function its own value:

def make_multipliers_default():
    return [lambda x, i=i: x * i for i in range(3)]

def make_multipliers_fixed():
    return [(lambda i: (lambda x: x * i))(i) for i in range(3)]

print([m(10) for m in make_multipliers_default()])
print([m(10) for m in make_multipliers_fixed()])
[0, 10, 20]
[0, 10, 20]
  • A default argument captures the value now, as the function is created.
  • An extra function layer (a factory) gives each closure its own i.

A plain factory such as make_adder(n) never has the problem, because each call has its own n.

7. Real uses

Memoize: remember results

A closure can hold a cache, which is how functools.lru_cache works in spirit (lessons 11.6 and 11.11):

def memoize(func):
    cache = {}

    def wrapper(n):
        if n not in cache:
            cache[n] = func(n)
        return cache[n]

    return wrapper

calls = []

def slow_square(n):
    calls.append(n)
    return n * n

fast = memoize(slow_square)
print(fast(4), fast(4), fast(5))
print(calls)
16 16 25
[4, 5]

slow_square ran only for 4 and 5. The second fast(4) was answered from the cache.

once: run only the first time

def once(func):
    done = False
    result = None

    def wrapper(*args, **kwargs):
        nonlocal done, result
        if not done:
            result = func(*args, **kwargs)
            done = True
        return result

    return wrapper

setup = once(lambda: print("setting up") or 42)
print(setup())
print(setup())
setting up
42
42

The message appeared once: the second call returned the saved 42 without running the function. (print(...) or 42 prints, then gives 42, because print returns None, which is false, lesson 5.3.)

Callbacks

When a button, a timer or a web request needs a function to call later, a closure lets that function remember the details of the moment it was created, such as which button, which user or which file. Note lambda label=label: ... from the loop trap section.

8. Lifetime

A variable kept alive by a closure lives as long as the closure does. If a function remembers a huge list, the list stays in memory until the function itself is gone. That is usually fine, but be aware of it with big data:

def make_big():
    data = list(range(5))
    return lambda: sum(data)

total = make_big()
print(total(), total.__closure__[0].cell_contents)
10 [0, 1, 2, 3, 4]

The list data is still there, inside total's cell, long after make_big has returned.

Worked example: a labelled logger

Make a logger factory whose log function remembers its label and a count of messages, and a dump function that shares the same list.

def make_logger(prefix):
    messages = []

    def log(msg):
        messages.append(f"{prefix}: {msg}")
        return len(messages)

    def dump():
        return list(messages)

    return log, dump

log, dump = make_logger("app")
print(log("start"))
print(log("stop"))
print(dump())

net_log, net_dump = make_logger("net")
net_log("connected")
print(net_dump())
print(dump())
1
2
['app: start', 'app: stop']
['net: connected']
['app: start', 'app: stop']
Part What it demonstrates
prefix and messages variables remembered by the closure
log and dump two functions sharing the same messages list
list(messages) in dump returns a copy, so callers cannot change the log (lesson 11.9)
make_logger("net") a second, independent logger with its own list

messages is changed with append, which does not rebind the name, so no nonlocal was needed (lesson 11.5). The labels and messages are made up.

Common mistakes

  • Forgetting nonlocal when the inner function must rebind (+=, =) an outer variable.
  • Creating functions in a loop and expecting each to keep its own loop value.
  • Expecting a closure to copy values. It shares the variable.
  • Using a closure when a class would be clearer as the state grows.
  • Keeping huge data alive by accident through a closure.

Key takeaways

  • A closure is an inner function that remembers variables from the enclosing function, even after it has returned.
  • Each call to the outer function creates a separate closure with its own variables.
  • Use nonlocal to rebind a remembered variable (counters, accumulators); changing a mutable object in place needs no nonlocal.
  • Closures give hidden, shared state without a class; choose a class when several operations share growing data.
  • Closures share variables, not values: bind the current value with a default argument or a factory in loops.

Practice

1. Write make_multiplier(n) that returns a function multiplying its argument by n.

Show answer
def make_multiplier(n):
    return lambda x: x * n

2. What does make_counter() return the second time you call the returned function, if it starts from 0?

Show answer

2. The closure keeps count between calls, so it goes 1, then 2.

3. What happens inside tick if you leave out nonlocal count?

Show answer

count += 1 makes count a local variable with no value yet, so Python raises UnboundLocalError.

4. Why do all functions in [lambda: i for i in range(3)] return 2?

Show answer

They share the single variable i, which is 2 at the end of the loop. Bind the value with lambda i=i: i.

5. Make a closure make_toggle() that returns True, False, True, ... on each call.

Show answer
def make_toggle():
    state = False
    def toggle():
        nonlocal state
        state = not state
        return state
    return toggle

6. When would you choose a class over a closure?

Show answer

When several operations share the same data, when you want the data to be visible and easy to inspect or extend, or when the code grows beyond one small function.