First-class functions & closures
Functions that remember
Lesson 3 of 20 · 10 min · Module 1: Functions, deeper
In Python, functions are values. You can store them, pass them to other functions, and create new ones inside a function. An inner function can remember the variables around it.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Treat functions as values
- Create a closure
- Change an enclosing variable with nonlocal
The idea
A closure is an inner function that keeps access to variables of the function that created it, even after that function has returned. To change such a variable from the inner function, declare it with nonlocal.
def make_multiplier(factor):
def multiply(x):
return x * factor
return multiply
triple = make_multiplier(3)
print(triple(5))
01Functions are objects
sorted(names, key=len) passes the function len as a value. You can also return a function from another function, as make_multiplier does.
02Closures remember
Each call of make_counter creates a new current variable and a new inner function bound to it. That is why two counters do not interfere.
def make_counter():
count = 0
def bump():
nonlocal count
count += 1
return count
return bump
a = make_counter()
print(a(), a())1 203Why nonlocal is needed
Assigning to a name inside a function normally creates a new local variable. nonlocal tells Python to update the variable from the enclosing function instead.
Your turn
make_counter(start=0, step=1) that returns a function. Each call of the returned function returns the next number: first start, then start + step, and so on. Two counters must count independently.What the checks look for
- Counts from the start value
- Uses a custom start and step
- Two counters are independent
Take this with you
A closure is a small object made of a function plus the variables it remembers.
Go a little further
Add a reset() function by returning a tuple of two closures that share the same variable.