Functions, closures, decorators

A function is an object, a closure captures a cell, and a decorator is just an assignment. Three facts from which you can derive late binding, the loss of a signature, a quiet leak through lru_cache, and why @property is built the same way as @staticmethod.

L1 · 9 minL2 · 11 min📱 phoneverified · CPython 3.11, linux x86-64

1Predict

Commit to an output and a reason before you open the answer.

Snippet A
fs = [lambda: i for i in range(3)]
print([f() for f in fs])

fs2 = [lambda i=i: i for i in range(3)]
print([f() for f in fs2])
[2, 2, 2]
[0, 1, 2]
One and the same expression; the difference is a single default argument.
Snippet B
def deco(f):
    def w(*a, **k): return f(*a, **k)
    return w

@deco
def target(x: int, y: str = "a") -> bool:
    "doc"
    return True

import inspect
print(target.__name__, target.__doc__)
print(inspect.signature(target))
w None
(*a, **k)
The name, the documentation and the signature — all of them someone else's.
Snippet C
def counter():
    n = 0
    def inc():
        nonlocal n
        n += 1
        return n
    return inc

c = counter()
c(); c()
print(c.__code__.co_freevars, len(c.__closure__))
('n',) 1
The function has a field that an ordinary function does not. What is in it?
Snippet D
from functools import lru_cache
class Heavy:
    def __init__(self): self.buf = bytes(200_000)
    @lru_cache(maxsize=None)
    def calc(self, x): return x * 2

import weakref, gc
h = Heavy(); w = weakref.ref(h)
h.calc(1)
del h; gc.collect()
print(w() is not None)
True
The object was deleted, the collector ran, the object is alive.

2Mechanism

Three facts, each of which sounds harmless on its own. Together they explain everything in this lesson.

A function is an object. It has attributes; it can be passed around, put into a list, given a field. The def statement executes and creates this object — as we already saw in lesson 01.

A closure captures a cell, not a value. An inner function that uses a name from the outer one gets a reference to a shared cell; at call time it reads whatever is in the cell right now.

A decorator is syntax for an assignment. @deco above def f means literally f = deco(f). The language has no separate entity called “decorator”.

Consequence 1 · late binding

Snippet A. All three lambdas refer to one cell — the loop variable's. By the time they are called the loop has long finished, and the cell holds 2. Nothing “broke” — the functions honestly read the current value, as the definition promises.

The lambda i=i variant works by a different mechanism: a default value is evaluated at the moment the function is created (lesson 01, consequence 3) and stored in __defaults__. So the fix happens not through the closure but around it.

Snippet C shows the cell itself. co_freevars lists the captured names, __closure__ stores the cells — an ordinary function simply does not have this field.

Consequence 2 · a decorator replaces the object entirely

Since @deco is f = deco(f), what comes out is another object. It has its own name, its own documentation, its own signature. The original function has not gone anywhere, but the name target now gives you the wrapper.

Snippet B is a direct consequence, not an oversight. functools.wraps copies the metadata from the original onto the wrapper and also puts a reference into __wrapped__, through which inspect.signature finds the real signature.

Hence a rule with no exceptions: a wrapper without wraps breaks everything that reads a function's metadata — help, the debugger, documentation, type-based dispatch, and any framework that builds behaviour from annotations.

Consequence 3 · a decorator with arguments has three levels

@deco(x) unfolds into f = deco(x)(f): first deco(x) is called, and its result is what gets applied to the function. So there are exactly three levels of nesting — one taking the settings, one taking the function, one taking the call.

This is not a convention but the arithmetic of how the syntax unfolds. And it also makes clear why @deco without parentheses and @deco() with them are different things, and why libraries that support both forms do it by branching inside.

Consequence 4 · where the cache holds the object

Snippet D. @lru_cache is an ordinary decorator applied in a class body, so the cache lives on the function, that is, on the class. The key is the tuple of arguments, and the first argument of a method is self. So the cache holds a strong reference to every instance the method was called for.

From lesson 09 we know that an object lives while there is a reference to it. The cache holds exactly that — until eviction, and with maxsize=None there is no eviction at all. A quiet leak in a long-lived process, visible only as growing memory.

And what ties all of this together

@property, @staticmethod and @classmethod are ordinary decorators. They are not built into the syntax: they are functions returning a descriptor object, which then works by the procedure from lesson 04. Three “magic” constructs turn out to be one mechanism — a decorator plus a descriptor — and there is no need to memorize them separately.

3Limits of the model

Where this stops holding

nonlocal and global are different things. The first binds a name to a cell of the nearest enclosing function, the second to the module. Without them an assignment inside a function creates a new local variable, and reading it before the assignment gives an UnboundLocalError, not the value from outside.

A closure retains everything it looks at. The cell holds the object, the object holds its graph — the mechanism from lesson 09 works here too. A closure that happened to capture self or a large data frame will retain it for as long as the function lives.

wraps does not copy everything. It carries over the name, the documentation, the module, the annotations and __dict__, but the wrapper remains another object: its id is different, and inspect.signature is honest only because it deliberately looks into __wrapped__. Code that compares functions by identity will still break.

4Root

Root R2 in its most direct form: a function is an object like everything else, and a name is simply bound to it. Decorators, closures, and the fact that @property needs no support in the syntax all follow mechanically from this.

The order in which things appeared is telling. Closures and nested functions were there almost from the start; the @ syntax was added only in 2.4 (PEP 318) — before that people wrote f = deco(f) by hand, and it worked exactly the same way. That is, the decorator appeared as a shorthand for an existing mechanism, not as a new capability. Likewise nonlocal, added only in Python 3: before it a closure could read an outer variable but not assign to it, and people made do with a mutable one-element list.

5Analogy

A closure in Python is a C++ lambda with capture by reference, and the analogy holds right down to the consequences. The cell plays the role of the captured reference: both look at the variable rather than its value, both see changes made after creation, both give a “surprising” result in a loop.

They part ways in one place, and that is instructive too. In C++ a capture by reference can outlive the variable and turn into a dangling reference — a classic source of undefined behaviour. In Python the cell keeps the object alive, because the reference count from lesson 09 is at work. The same technique, but one memory model makes it dangerous and the other merely counter-intuitive.

6Questions a careful reader asks

Questions that come up on their own if you read closely. The answer is under the question.

Why does a closure capture the variable rather than the value?

Because what is captured is the cell, not its contents — and that is the same decision that makes nonlocal possible.

The classic trap:

fs = [lambda: i for i in range(3)]
print([f() for f in fs])       # → [2, 2, 2]

fs = [lambda i=i: i for i in range(3)]
print([f() for f in fs])       # → [0, 1, 2]

All three lambdas look into one cell, and by the time they are called it holds the last value. The second variant works because the default is evaluated at the moment the lambda executes — the very early binding from lesson 01, here put to its intended use.

Why capture by value was not chosen. Then a closure that changes an outer variable would be impossible — counters, accumulators, stateful decorators. Two different capture syntaxes would have to be introduced, as in C++ ([=] and [&]). Python chose one rule and an explicit workaround through the default.

It is visible right in the code object:

def outer():
    n = 0
    def inner(): return n
    return inner
print(outer().__code__.co_freevars)          # → ('n',)
print(outer().__closure__[0].cell_contents)  # → 0

cell_contents is the cell's contents, and the cell itself is one for everyone who captured it.

Why functools.wraps, if the decorator works without it?

It works — until the first encounter with introspection, and half of all tools stand on that.

Without wraps the decorator replaces the function object, and what sticks out is the wrapper with its own name, its own docstring and the signature (*a, **k):

import functools, inspect

def bare(fn):
    def w(*a, **k): return fn(*a, **k)
    return w

def kept(fn):
    @functools.wraps(fn)
    def w(*a, **k): return fn(*a, **k)
    return w

@bare
def f(x: int) -> int:
    "adds"
    return x

@kept
def g(x: int) -> int:
    "adds"
    return x

print(f.__name__, f.__doc__, inspect.signature(f))
# → w None (*a, **k)
print(g.__name__, g.__doc__, inspect.signature(g))
# → g adds (x: int) -> int

What really breaks: error messages and logs show w instead of the function's name; help() and Sphinx lose the documentation; pytest gets confused about fixtures; typing.get_type_hints finds no annotations; caches and dispatchers keyed by __qualname__ glue different functions into one.

On top of that, wraps keeps __wrapped__ — through it inspect gets to the original function through any number of layers. That is the only reason inspect.signature returned the right signature in the example above.

Why is lru_cache on a method a leak?

Because the cache lives on the class, and self ends up in it as part of the key.

The decorator is applied to the function in the class body, that is, once per class, not per instance. The first argument of a method is the object itself, so it becomes part of the key and is retained by the cache through a reference. The instance will not die until the cache evicts its entry, and with maxsize=None — never.

import functools, gc, weakref

class Heavy:
    def __init__(self): self.data = bytearray(10**6)
    @functools.lru_cache(maxsize=None)
    def compute(self, k): return k * 2

h = Heavy()
r = weakref.ref(h)
h.compute(1)
del h
gc.collect()
print(r())          # → the object is alive, although the code holds no references

In production this looks like a service whose memory grows linearly with the number of objects processed, and the profiler honestly shows them as reachable — because they are reachable.

What to do. Cache a free function that takes only immutable arguments, and call it from the method. Or functools.cached_property, if the value depends only on the object — there the cache sits in the object itself and dies with it. Or an explicit dictionary on the instance. For methods where the key is only the arguments, not the state, a @staticmethod with lru_cache will do.

functools.cached_property has existed since 3.8, and 3.12 added a warning about this mistake to the documentation — but not to the code: the language still does not catch it.

Why does a decorator with arguments require three levels of nesting?

Because @dec(arg) is not special syntax but first a call, then decoration.

The line @retry(3) unfolds into f = retry(3)(f). That is, retry(3) must return a decorator, and that in turn returns the wrapper. Hence exactly three levels: parameters → function → call arguments.

import functools

def retry(times):                      # 1. takes the parameters
    def decorator(fn):                 # 2. takes the function
        @functools.wraps(fn)
        def wrapper(*a, **k):          # 3. takes the call arguments
            for attempt in range(times):
                try: return fn(*a, **k)
                except Exception:
                    if attempt == times - 1: raise
        return wrapper
    return decorator

@retry(3)
def flaky(): ...

Hence also the most common mistake — a decorator that wants to work both with and without arguments: @retry and @retry(3) at once. That requires telling “I was given a function” from “I was given a parameter”, and is usually written with a callable(first argument) check. It reads badly; it is simpler not to support both forms.

A cleaner alternative, if the nesting gets in the way, is a class with __call__: the parameters live in __init__, the wrapper in __call__, two levels. But then you have to restore __name__ and __doc__ by hand, and on methods a class decorator behaves differently, because it is not a descriptor.

Bottom line. A function is an object created by executing def; a closure captures a cell, not a value; a decorator is syntax for f = deco(f). From the first it follows that functions can be passed around and given fields. From the second — late binding: all the lambdas in a loop look into one cell and read it at call time, and the lambda i=i technique fixes that around the closure, by evaluating a default at creation. From the third — that what comes out is another object with its own name, documentation and signature, and without functools.wraps everything that reads metadata breaks: help, the debugger, dispatch, annotation-driven frameworks. And from there too comes lru_cache on a method: the cache lives on the class and holds self as a key, that is, it does not let instances die. And @property, @staticmethod and @classmethod are not syntax but the same kind of decorators, returning the descriptors of lesson 04.
From here on — optional
counterfactualC++ lambdas, Java, JavaScriptExplicit capture [=] and [&] versus the single option in Python

C++ is the most precise comparison, because the choice of capture there is explicit. [=] copies the value at the moment the lambda is created, [&] captures by reference. Python always does the second: capture by cell, that is, [&] with no alternative. Hence the late binding of consequence 1 — in C++ exactly the same behaviour comes with [&], and it catches beginners in exactly the same way, only there the reference can also outlive its scope and dangle. Python is protected from the latter by the reference count: the cell keeps the object alive.

The lambda i=i: i technique is a hand-made emulation of [=]: copy the value at the moment of creation. If you know C++, the construct stops looking like a trick.

JavaScript went through the same pain and solved it at the language level: var behaved like Python, while let in a loop creates a new binding on every iteration. Python did not do that — and will not, because of R9.

Java required the captured variable to be effectively final. The problem was removed by banning the situation — the same technique as with multiple inheritance.

🐛 bugA wrapper without wraps breaks the frameworkThe signature turns into (*a, **k) — annotation-based validation and dependency injection stop working

A custom logging decorator was written. The endpoints stopped receiving their parameters.

def logged(f):
    def w(*a, **k):
        log.info("calling %s", f.__name__)
        return f(*a, **k)
    return w

@app.get("/items/{item_id}")
@logged
def read_item(item_id: int, q: str | None = None): ...

The framework builds a route by reading the function's signature: which parameters come from the path, which from the query, which types to coerce. But what it sees is not read_item but the wrapper:

print(inspect.signature(read_item))
# → (*a, **k)
print(read_item.__name__)
# → 'w'

What happens next depends on the framework: somewhere an error at startup, somewhere the parameters silently arrive empty, somewhere an endpoint with arguments a and k appears in the API docs. Review lets it through because the decorator is written by the book and works in a unit test of the function itself — what breaks is only the link with whoever reads the metadata.

import functools

def logged(f):
    @functools.wraps(f)
    def w(*a, **k):
        log.info("calling %s", f.__name__)
        return f(*a, **k)
    return w

The rule from consequence 2, with no exceptions: every wrapper around a function gets @functools.wraps. It costs one line, and its absence shows up in the most unexpected places — from an empty line in a traceback to a broken OpenAPI schema.

⚡ costA decorator is not free, but lru_cache pays for itselfA wrapper doubles the cost of a call; a cache on recursion turns 0.2 s into microseconds

Two sides of the same coin: you pay for a decorator on every call, but sometimes it gives back thousands of times more.

The cost of a wrapper. A trivial function called directly and through the simplest possible decorator:

2,000,000 callstime
directly0.109 s
through a wrapper0.257 s

Two and a half times — because there are two calls instead of one, plus packing *a, **k. On a function doing real work this is lost in the noise; on a micro-function in a hot loop it is not. The practical conclusion: do not decorate what is called millions of times and itself costs nanoseconds.

When a wrapper pays for itself. The same mechanics, but with a cache, on a recursive function:

fib(25), 20 runstime
without a cache0.202 s
with @lru_cache after warm-up0.000004 s

The wrapper costs the same nanoseconds, but replaces an exponential tree of calls with one dictionary lookup. This is not an optimization of the function but a change of complexity class — like choosing the data structure in lesson 03.

Two conditions of applicability, both derived from the mechanism: the arguments must be hashable (lesson 05), and the cache must not be put on methods — consequence 4 shows what that costs. For methods there is cached_property for immutable objects, or an explicit cache in the instance itself.

💻 terminalCheck it in the REPLFour snippets plus UnboundLocalError, the order of decorators, and a cell after exit

Run the four snippets and check them against your prediction. Then:

x = 1
def f():
    print(x)
    x = 2
f()
# Why an UnboundLocalError, if print comes first?

def a(f): print("a"); return f
def b(f): print("b"); return f
@a
@b
def g(): pass
# In what order will it print, and why exactly that way?

def make():
    data = list(range(1_000_000))
    return lambda: len(data)
f = make()
# How much memory does f retain? And if you return lambda: 0?

property.__get__, staticmethod.__get__
# Make sure both are descriptors. What does that prove?

The first question is the most useful one: a name becomes local at the function's compile time, not at the moment of assignment, and that is visible in f.__code__.co_varnames.

sourcefunctools and dataclassesWhat wraps looks like inside, and why dataclass generates code as a string

Lib/functools.py, wraps and update_wrapper. Twenty lines worth reading in full: the list of copied attributes is given by the explicit tuples WRAPPER_ASSIGNMENTS and WRAPPER_UPDATES, and at the end there is the assignment wrapper.__wrapped__ = wrapped. It is exactly this line that lets inspect.signature reach the original. Notice that the language has no mechanism for “inheriting metadata” — everything is done by copying by hand.

Lib/dataclasses.py. The most interesting part is here: to generate an __init__ with the right signature, the standard library assembles the function's source text as a string and runs exec. The reason is right in consequence 2 — a wrapper of the form def __init__(*a, **k) would have the wrong signature, and it cannot be faked; only a real def gives a real signature. It also shows that dataclass is a class decorator, that is, the lightest level of intervention from lesson 07.

L2Cells, MAKE_FUNCTION and the cost of a callHow the compiler decides a variable is free, and what is in __closure__

From L1 you know about the cell. Here: who creates it and when.

The decision is made by the compiler, not the runtime. Taking a function body apart, it classifies every name: local, free (used here, defined in an outer function), cell (defined here, used in a nested one) or global. The result sits in the code object:

print(c.__code__.co_freevars)       # what was captured
# → ('n',)
print(counter.__code__.co_cellvars)  # what was handed to nested functions
# → ('n',)
print(c.__closure__[0].cell_contents)
# → 2

Hence the answer to the UnboundLocalError question: since a name is classified at compile time, an assignment anywhere in the body makes the name local for the whole function, including the lines before the assignment.

Creating a function is the MAKE_FUNCTION instruction, which attaches a tuple of cells when needed. That means every execution of def creates a new function object: a nested function defined in a loop is N objects, not one. Hence the overhead of function factories in hot code.

About the cost of a call: the difference of 0.109 s versus 0.257 s from the “In practice” section is made up of a second call frame, packing the arguments into a tuple and a dictionary, and unpacking them again. Since 3.11 frames have become cheaper, so on newer versions the gap is smaller — check on your own.

L3Where this is in the CPython sourcesfuncobject.c, cellobject.c, symtable.c — three files that close the lesson

Tag v3.11.15.

  • Objects/cellobject.c — the whole cell type, a hundred and fifty lines. It is built as simply as possible: one pointer, and that is literally the “reference to an object” discussed in lesson 01.
  • Python/symtable.c — classifying names at compile time: local, free, cell, global. This is where the decision that produces UnboundLocalError is made.
  • Objects/funcobject.c, func_new_impl — what a function object consists of: code, globals, defaults, closure, annotations.
  • PEP 318 — the introduction of the @ syntax in 2.4; the motivation says outright that the mechanism already existed and only the notation is being added.
connectionsWhere this leadsL01, L04, L07, L09 · the contrast with explicit capture in C++ and let in JavaScript
root R2 · Attributes are resolved at runtime, a namespace is a dict
← foundation L01 · Name, object, reference — “a function is an object”, and defaults evaluated at creation
← foundation L04 · obj.x, end to end — property and staticmethod as descriptors
← foundation L09 · Reference counting — why a cache on a method does not let an instance die
↔ contrast C++ lambdas: [=] versus [&], there is a choice — in Python there is none
↔ contrast let in JavaScript: the same problem, solved by changing the language
→ next L07 · Metaclasses — a class decorator as the lightest level of intervention
not covered here Generators and coroutines — also objects with a frame, but that is a separate protocol; R5
readingFurther readingwraps and update_wrapper 🟧 · PEP 318 🟦 · dataclasses.py 🟥

Written by · The Python Canon