the full guide

First-class functions and closures

In Python, functions are first-class: they can be stored in variables, passed to other functions and returned from functions. A closure is a function that remembers variables from the place where it was created, even after that place has finished running.

8 min Intermediate

What you need: The earlier topics of this module.

Definition

In Python, functions are first-class: they can be stored in variables, passed to other functions and returned from functions. A closure is a function that remembers variables from the place where it was created, even after that place has finished running.

In simple words

A function is just a value, like a number. A closure is a function with a backpack: when it left home, it took some values along, and it can still use them later.

Why it matters

Decorators, callbacks and functions like sorted(key=...) all depend on this. It lets you make small factory functions in place of whole classes.

How it works

In code

closures.py
def shout(text):
    return text.upper()

say = shout                 # a function stored in a variable
print(say("hello"))

def apply(func, value):     # a function passed to a function
    return func(value)
print(apply(len, "hello"))

def make_multiplier(n):     # a function returned from a function
    def multiply(x):
        return x * n        # remembers n
    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5), triple(5))

late = [lambda: i for i in range(3)]
print([f() for f in late])
fixed = [lambda i=i: i for i in range(3)]
print([f() for f in fixed])

Output

HELLO
5
10 15
[2, 2, 2]
[0, 1, 2]

Common mistakes

  • The late-binding trap in loops, shown in the code above.
  • Writing func() when passing a function. func() calls it. Pass func.

Check yourself

Question 1

1. What does sorted(names, key=len) pass as key?

Question 2

2. What is a closure?

Summary

  • Functions are values you can store, pass and return.
  • Closures remember variables from where they were created.

Finished reading?

Sources: The Python Tutorial, python.org