Closures & first-class functions

P29.functions-closures.01 · Audience: guest, it-ml, language-pro

Real LLM grading for this pageLLM grading (this page):

Welcome to Functions, Decorators & Generators — the second pillar of the Advanced Python discipline. Everything in this pillar grows from one idea: in Python, a function is a value like any other. This module builds that idea up to the closure — a function that carries its own private state — and the factory pattern interviewers love to probe.

Step 1 / 4Functions are values
ⓘ Concept: First-class means passable
A def statement creates a function object and binds it to a name. That object can be assigned, stored in a list, passed as an argument (sorted(words, key=len)), and returned from another function. Nothing special happens at the call site — a function is data until you add ().

Why it matters — Sorting with key=, callbacks, decorators, functools — every advanced idiom starts from the fact that a def produces an object you can hand around.

Ask the mentor about this module

Ask a question about this content. The mentor explains and grounds its answer in what you are studying; asking is recorded as a learning signal, not a grade.

Ctrl/Cmd + Enter to send

🎓 Practice ladder

3 graded rungs · ~26 min

Your turn: build a counter factory with nonlocal, then rebuild composition and partial application by hand, and close with the interview question every Python screen asks about closures.

Rung 1 — a counter factory with nonlocal

Loading exercise…

Rung 2 — compose and partially apply

Loading exercise…

Interview rung — what does a closure capture? (free-form)

Loading exercise…

By the end you should be able to predict, out loud, what a loop full of lambdas returns and why — and fix it two different ways without hesitating.