A function that remembers.
Capture a small piece of configuration and return a function tailored to it.
01 The idea
A closure is a function that retains access to variables from an enclosing function scope. This makes it possible to prepare a small operation with configuration and pass that operation elsewhere. Capturing a variable is not the same as copying its current value: when names are rebound, that distinction matters.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
def make_prefixer(prefix):
def format_name(name):
return f"{prefix}: {name}"
return format_name
label = make_prefixer("LAB")
print(label("Orbit"))
print(label("Atlas"))LAB: Orbit LAB: Atlas
03 Under the hood
- 1
make_prefixer finishes, but the returned function still has access to prefix. The caller only needs the simple name argument now.
- 2
Each call to make_prefixer can create a distinct configured function. Keep captured data small and clear so the lifetime of that data is unsurprising.
- 3
If an inner function must rebind a name from the enclosing function, declare it nonlocal. For complicated state and multiple operations, a class may communicate the design more clearly.
04 Your turn, builder
Create a multiplier factory and use it to produce a function that triples a value.
Reveal one possible solution +
def multiplier(factor):
def apply(value):
return value * factor
return apply
triple = multiplier(3)
print(triple(7))05 Check your signal
What can a closure retain?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.