Lesson 3 of 5 · Advanced Python · 2 min read · Updated

Closures

Functions that remember values from where they were created.

python
def make_multiplier(factor):
    def multiply(n):
        return n * factor
    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5), triple(5))
Output
10 15

make_multiplier has finished running, yet double still knows its factor was 2. An inner function that keeps the variables of the function around it is a closure. It is a way to build many similar functions from one template.

Changing a remembered value

python
def make_counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

counter = make_counter()
counter()
counter()
print(counter())

other = make_counter()
print(other())
Output
3
1

nonlocal is the E in LEGB: it lets the inner function assign to the enclosing function's variable instead of creating a local one. Each call to make_counter() creates a separate, private count.

The late binding trap

python
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])

funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs])
Output
[2, 2, 2]
[0, 1, 2]

Warning

A closure remembers the variable, not its value at that moment. All three lambdas look up i when they are called — after the loop, when it is 2. Binding it as a default argument, i=i, captures the value at creation time.

add5 = make_adder(5), where make_adder returns an inner function using its argument. What makes add5 remember 5?

Try this now

  1. Write make_greeter(greeting) that returns a function greeting any name, and make one for "Vanakkam" and one for "Hello".
  2. Write make_bank(balance) returning deposit and withdraw functions that share one private balance.

Create a free account to save your progress, or sign in.