Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Advanced Python & Software Engineering — Alpha School

Lesson 10: First-Class Functions and Closures

In Python, functions are first-class objects: you can store them in variables, pass them as arguments, return them from other functions, and keep them in lists and dictionaries, exactly like numbers or strings. This is not a party trick — it is the foundation of some of Python's most useful patterns. Sorting with a key function, for example, works because sorted() accepts a function and calls it on each item. The moment you start treating functions as values, a whole set of new designs opens up.

A function that returns another function creates a closure: the inner function remembers the variables from the scope where it was defined, even after the outer function has finished running. In the example below, make_multiplier(3) returns a function that multiplies by 3, and make_multiplier(10) returns one that multiplies by 10. Each returned function carries its own copy of factor with it. That captured memory is the closure, and it is the mechanism that makes decorators — the subject of Lesson 12 — possible.

def make_multiplier(factor):
    def multiply(number):
        return number * factor
    return multiply


times_three = make_multiplier(3)
times_ten = make_multiplier(10)
print(times_three(7))  # 21
print(times_ten(7))    # 70

# Functions as arguments: sort words by length, longest first
words = ["fig", "banana", "kiwi", "pineapple"]
print(sorted(words, key=len, reverse=True))
# ['pineapple', 'banana', 'kiwi', 'fig']

# A small function written inline: lambda
squares = list(map(lambda x: x * x, [1, 2, 3]))
print(squares)  # [1, 4, 9]

lambda and the limits of cleverness

A lambda is a tiny anonymous function, written inline: lambda x: x * x. It can only hold a single expression, which makes it perfect for short keys and callbacks, and painful for anything longer. The style guide for this course is simple: use a lambda when the logic fits comfortably on one line and is obvious at a glance, and write a proper def the moment it is not. A named function can have a docstring, can be tested, and can be reused — a lambda can do none of those things.

Closures have one classic trap worth knowing now. If you create several closures inside a loop, they all share the loop variable — they do not each capture the value it had when they were created. So a list of functions built in a loop over range(3) will all see the final value, 2, when called later. The usual fix is to bind the value as a default argument, as in lambda x, n=n: x * n, or to build the closure through a helper function like make_multiplier. It is a small detail, but it is the kind of thing that produces a baffling bug exactly once — and then you never forget it.

Going further

First-class functions make a useful design pattern possible: the dispatch table. Instead of a long chain of if and elif statements choosing what to do, you store functions in a dictionary keyed by a command name, and look the function up when the command arrives. A tiny calculator, for example, can map "+" to one function, "-" to another, and so on — and adding a new operation means adding one dictionary entry, not editing a chain of conditions. The pattern appears everywhere: web frameworks dispatch requests this way, and command-line tools dispatch subcommands the same way.

Closures are also the engine behind the next lesson's decorators, so it is worth being sure the idea is solid. A decorator is a function that takes a function and returns a new function — and the new function is a closure, remembering the original function from the scope where it was defined. When you see @timer above a function, what is really happening is that timer receives the function, builds a closure around it, and hands the closure back under the same name. Everything in the next two lessons is an application of the two ideas in this one.

Closures appear in a surprising place: graphical interfaces and event handling. When a button is clicked, the program calls a function you registered earlier — and that function is often a closure that remembers which button it belongs to, or which data it should act on. The same pattern drives callbacks in web frameworks and in asynchronous code. Whenever you see a function that is defined now but called later, with some remembered context, you are looking at a closure, whether or not anyone uses the word. Recognising the pattern in the wild is the step that turns a textbook idea into a tool you actually reach for.

Key Terms

First-class function
A function treated as an ordinary value: stored, passed as an argument, or returned from another function.
Closure
An inner function that remembers the variables of the scope where it was defined, even after that scope has ended.
Higher-order function
A function that takes another function as an argument or returns one, such as sorted() with a key.
lambda
A small anonymous function written inline, limited to a single expression.
key function
A function passed to sorted() or similar, called on each item to decide its ordering.
Free variable
A variable used inside a nested function but defined in an enclosing scope, captured by the closure.
Late binding
Closures sharing a loop variable see its final value, not the value at the time each closure was created.

Discussion Questions

  1. Why does sorted(words, key=len) need a function as an argument, rather than just sorting the words directly?
  2. Where have you already used a closure without knowing it — for example, a function defined inside another function?
  3. When is a lambda the right choice, and when should you write a named function instead? Give an example of each.

Practice Questions

  1. What does make_multiplier(3) return?
  2. What does sorted(["bb", "a", "ccc"], key=len) return?
  3. Write a lambda that returns the square of its argument.
  4. Why do closures created in a loop all see the loop variable's final value?
  5. Write a function make_adder(n) that returns a function adding n to its argument.
Show answers
  1. A function that multiplies its argument by 3. The inner function multiply closes over factor=3 and is returned, not called.
  2. ['a', 'bb', 'ccc']. The key function len is applied to each word, and sorting uses those lengths.
  3. lambda x: x * x. A lambda holds a single expression, which becomes its return value.
  4. Because of late binding: they share the variable, not a copy of it. Fix it by binding the value as a default argument or through a helper function.
  5. def make_adder(n): def add(x): return x + n return add The inner function closes over n; each call to make_adder creates an independent adder.
Keep reading to complete this lesson