Skip to content
BIASED

Closures and decorators

Functions as objects, closures and cells, the late-binding trap in loops, decorators as f = deco(f), functools.wraps, decorators with arguments, cache, lru_cache and partial, registries and the decorators of ML code.

A function is an object too

The topic The data model showed that a call x(...) is one more protocol: Python looks up __call__ on the type of x. An instance of a class with __call__ behaves like a function that remembers something between calls, such as a factor or a counter. Python's own functions are objects too, of type function. This topic shows that they can remember state without any class, and how that memory is used to wrap one function in another.

def creates a function object and binds a name to it, like any assignment in the topic Values, types and names. The object can then be bound to other names, stored in containers and passed to other functions:

def square(x):
    """Return x squared."""
    return x * x
 
f = square
print(f(7), f is square, f.__name__, f.__doc__)
print(type(square))
ops = {"sq": square, "neg": lambda x: -x}
print(ops["neg"](5))
print(sorted(["pear", "fig", "banana"], key=len))
49 True square Return x squared.
<class 'function'>
-5
['fig', 'pear', 'banana']

f = square copies nothing. Both names refer to one object, and its __name__ is the name that def gave it. A lambda is the expression form of def, limited to a single expression, and it creates the same kind of object. A function that takes or returns functions, as sorted takes key=len, is called a higher-order function.

A function object carries more than its code. __code__ holds the compiled code and the names of its variables. __defaults__ holds the default values, computed once when def ran; that is the source of the mutable-default trap from the topic Functions. A function defined inside another function has one more attribute, __closure__, and the rest of the topic grows out of it.

Closures and cells

The topic Functions placed nonlocal in the LEGB rule: a nested function sees the variables of the enclosing one and can rebind them. Here is what that gives us. A factory returns a function that keeps the running mean of the losses it has seen:

def make_mean():
    total = 0.0
    count = 0
    def update(loss):
        nonlocal total, count
        total += loss
        count += 1
        return total / count
    return update
 
train, val = make_mean(), make_mean()
print(train(1.0), train(0.5), train(0.0), val(2.0))
print(train.__code__.co_freevars)
print([c.cell_contents for c in train.__closure__])
1.0 0.75 0.5 2.0
('count', 'total')
[3, 1.5]

Two things are worth a second look. make_mean has returned and its frame is gone, yet update still reads and writes total and count. And train and val keep separate means.

The rule. When the compiler sees that an inner function uses a variable of the enclosing one, it does not keep that variable as an ordinary local of the enclosing frame. It puts it in a cell, a small object that holds one reference. Both functions read and write the variable through the cell. When def update runs, the new function object receives the tuple of its cells, __closure__. The names of those variables are its free variables, co_freevars. A function together with the cells it carries is a closure. The cell outlives the frame because the function still refers to it. Each call of make_mean creates new cells and a new update, hence two independent means. (Printing a cell itself shows memory addresses, which change from run to run.)

A closure does the job of a class with __call__ in less code, when the state is a variable or two and the behaviour is one function.

Why nonlocal is needed. Reading an enclosing variable needs nothing. Assigning to it does, because an assignment anywhere in a function makes the name local to that function, and this is decided when the function is compiled. Remove the declaration:

def make_counter():
    count = 0
    def increment():
        count += 1
        return count
    return increment
 
make_counter()()
Traceback (most recent call last):
  ...
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

count += 1 reads count before it assigns it, and count is already a local of increment with no value yet. nonlocal count declares that the name refers to the enclosing variable, that is, to its cell.

The late-binding trap

A closure stores the variable, not the value the variable had when the inner function was created. It reads the variable when it is called. This is late binding, and in loops it sets a trap. Here a comprehension builds three learning-rate schedules, one per base rate:

schedules = [lambda epoch: lr * 0.5 ** epoch for lr in [0.1, 0.01, 0.001]]
print([s(0) for s in schedules])
[0.001, 0.001, 0.001]

All three lambdas refer to one variable lr, held in one cell: schedules[0].__closure__[0] is schedules[2].__closure__[0] is True. By the time they are called, the loop is over and lr holds its last value. A def inside a for loop behaves the same way. At module level a loop variable is a global rather than a cell, but the rule does not change: the name is looked up when the function runs, so a later assignment changes what every such function sees.

The symptom is easy to recognize: several functions created in a loop all behave like the last one. The cure is to give each function its own value at creation time. There are two common ways:

fixed = [lambda epoch, lr=lr: lr * 0.5 ** epoch for lr in [0.1, 0.01, 0.001]]
print([s(0) for s in fixed])
 
def make_schedule(lr):
    return lambda epoch: lr * 0.5 ** epoch
 
print([s(1) for s in [make_schedule(lr) for lr in [0.1, 0.01, 0.001]]])
[0.1, 0.01, 0.001]
[0.05, 0.005, 0.0005]

A default value is evaluated when the lambda is created, so lr=lr copies the current value into a parameter of each function. A factory such as make_schedule creates a fresh cell on every call. The same trap waits for callbacks and hooks registered in a loop, which training code does often.

Decorators: f = deco(f)

Suppose several functions must report their arguments and results while we chase a bug. The direct way is to edit each of them:

def mse(y, t):
    result = (y - t) ** 2
    print(f"mse{(y, t)} -> {result!r}")
    return result
 
def mae(y, t):
    result = abs(y - t)
    print(f"mae{(y, t)} -> {result!r}")
    return result

The tracing lines repeat in every function, they bury the one line that does the work, and removing them later means editing every function again. We would rather write the tracing once and apply it from outside. That takes a function that receives a function and returns a new one that remembers the old one. A closure does exactly that.

A decorator is a callable that takes a function and returns its replacement. The replacement is usually a closure, called a wrapper, that calls the original:

def logged(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        print(f"{func.__name__}{args} -> {result!r}")
        return result
    return wrapper
 
@logged
def mse(y, t):
    """Squared error of one prediction."""
    return (y - t) ** 2
 
print(mse(3.0, 1.0))
print(mse.__name__, mse.__doc__)
mse(3.0, 1.0) -> 4.0
4.0
wrapper None

The key idea. @logged above def mse means mse = logged(mse), and it runs once, when the definition executes. Python creates the original function, passes it to logged and binds the name mse to whatever logged returns. Inside logged, the parameter func lives in a cell, because wrapper uses it. So the original is still alive, in the closure of the wrapper, and mse.__closure__[0].cell_contents is that original. The original function does not change. The name now refers to another object.

Two consequences follow:

  • Decorator code runs at definition time. In a module, that is when the module is executed or imported, before any call.
  • *args, **kwargs make a wrapper universal. It does not know the signature of the function it wraps, so it accepts any arguments and passes them on unchanged, the packing and unpacking from the topic Functions.

wraps and stacked decorators

The output above has a flaw. After decoration, mse.__name__ is 'wrapper' and the docstring is gone, so help(mse), log lines and any tool that reports a function by its name show the wrong thing. functools.wraps is a decorator for the wrapper that copies the original's metadata onto it:

import functools
import inspect
 
def logged(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        print(f"{func.__name__}{args} -> {result!r}")
        return result
    return wrapper

Applied to the same mse, it keeps the name, the docstring and the signature:

@logged
def mse(y, t):
    """Squared error of one prediction."""
    return (y - t) ** 2
 
print(mse.__name__, mse.__doc__, inspect.signature(mse))
mse Squared error of one prediction. (y, t)

wraps copies __name__, __qualname__, __doc__, __module__ and a few more attributes, and merges the function's attribute dictionary. It also adds __wrapped__, a reference to the original function. inspect.signature follows __wrapped__, which is why it shows (y, t) and not (*args, **kwargs). Use wraps in every decorator that returns a wrapper.

Stacking. Several decorators above one def apply from the bottom up: the one nearest the def goes first.

def bold(f):
    return lambda: "<b>" + f() + "</b>"
 
def italic(f):
    return lambda: "<i>" + f() + "</i>"
 
@bold
@italic
def hello():
    return "hi"
 
print(hello())
<b><i>hi</i></b>

This is hello = bold(italic(hello)). Order matters whenever decorators interact. A cache placed above a timing decorator stores the timed function, so calls answered from the cache are not timed at all. Placed below it, the cache leaves timing on every call.

Decorators with arguments

@over_seeds([0, 1, 2]) looks like a decorator with arguments. There is no special syntax behind it. The expression after @ is evaluated first, and its result is the decorator. So over_seeds([0, 1, 2]) must return a decorator, which takes one more level of nesting. This one runs an experiment once per random seed:

import functools
 
def over_seeds(seeds):
    def decorate(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            return [func(*args, seed=s, **kwargs) for s in seeds]
        return wrapper
    return decorate
 
@over_seeds([0, 1, 2])
def run(lr, seed):
    return f"lr={lr} seed={seed}"
 
print(run(0.1))
['lr=0.1 seed=0', 'lr=0.1 seed=1', 'lr=0.1 seed=2']

The decorated definition means run = over_seeds([0, 1, 2])(run). Three functions play three roles. over_seeds receives the decorator's arguments, decorate receives the function, and wrapper receives the arguments of each call. Each inner function is a closure over the variables of the outer ones: wrapper reaches seeds and func through cells. Library decorators of this kind are shown in their documentation with parentheses, and the parentheses matter.

Caching: functools.cache and partial

functools.cache is a decorator from the standard library. It stores each result under its arguments and returns the stored result when the same arguments come again. Its classic customer is a recursion that recomputes the same values:

import functools
 
@functools.cache
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)
 
print(fib(25))
print(fib.cache_info())
75025
CacheInfo(hits=23, misses=26, maxsize=None, currsize=26)

How much does the cache save? Without it, let c(n)c(n) be the number of calls that fib(n) makes, itself included. Then c(0)=c(1)=1c(0) = c(1) = 1, and for n≥2n \ge 2 a call counts itself plus its two recursive calls:

c(n)=1+c(n−1)+c(n−2).c(n) = 1 + c(n-1) + c(n-2).

Adding 1 to both sides shows that c(n)+1c(n) + 1 satisfies the Fibonacci recurrence, starting from c(0)+1=c(1)+1=2c(0) + 1 = c(1) + 1 = 2. With Fibonacci numbers F1=F2=1F_1 = F_2 = 1, F3=2F_3 = 2 and so on, this gives

c(n)=2Fn+1−1.c(n) = 2F_{n+1} - 1.

That is 177 calls for n=10n = 10 and 242,785 for n=25n = 25, growing like 1.618n1.618^n. With the cache, the body runs once for each kk from 0 to nn: those are the n+1n + 1 misses, 26 for n=25n = 25. Every other call is a dictionary lookup. On a laptop the plain fib(25) takes a few milliseconds and the cached one a few hundredths of a millisecond. Timings vary between machines and runs; the call counts do not.

The rules follow from "the arguments are the key":

  • Arguments must be hashable, as in the topic Dictionaries and sets. fib([1]) raises TypeError: unhashable type: 'list'.
  • cache never forgets. @functools.lru_cache(maxsize=128) keeps only the 128 most recently used results, which bounds memory. fib.cache_clear() empties either.
  • Only for pure functions. A cached function that reads a file, the clock or a global variable returns a stale answer after they change.

functools.partial fixes some arguments of a function and returns a callable that takes the rest. It captures the values when it is created, so it is a third cure for late binding:

def schedule(epoch, lr):
    return lr * 0.5 ** epoch
 
fns = [functools.partial(schedule, lr=lr) for lr in [0.1, 0.01, 0.001]]
print([f(0) for f in fns])
[0.1, 0.01, 0.001]

Decorators in ML code

A decorator applies to a class with the same meaning: @deco above class C is C = deco(C). @dataclass from the topic Classes and objects is one; it reads the annotations and adds __init__, __repr__ and __eq__. A decorator does not have to wrap anything either. A registry decorator records a class in a dictionary and returns it unchanged:

MODELS = {}
 
def register(name):
    def decorate(cls):
        MODELS[name] = cls
        return cls
    return decorate

Each model class registers itself under a short name:

@register("linear")
class Linear:
    def __init__(self, n):
        self.n = n
 
@register("mlp")
class MLP(Linear):
    pass

A training script can then build a model from a string in its config, with no if for each model:

config = {"model": "mlp", "width": 16}
model = MODELS[config["model"]](config["width"])
print(sorted(MODELS), type(model).__name__, model.n)
['linear', 'mlp'] MLP 16

Libraries such as timm and MMDetection organize models, datasets and losses this way. Other decorators you will meet in ML code:

  • @torch.no_grad() turns off gradient recording inside the decorated function, usually an evaluation function. The same object works as with torch.no_grad():, because its class defines both the context-manager methods from The data model and a __call__ that wraps a function. contextlib.ContextDecorator does the same in the standard library.
  • @property, @classmethod, @staticmethod from the topic Classes and objects.
  • @functools.cache on a function that loads a tokenizer or a vocabulary, so it is built once.
  • @pytest.fixture and @pytest.mark.parametrize, which register test helpers (see the topic Testing).

A registry has a catch. It fills up only when the module with the decorated classes is executed. A model defined in a file that nobody imported is simply not in MODELS. Real projects spread over many files and depend on code that other people wrote. The next topic, Modules, packages and environments, follows import from the statement to the file it finds and shows how environments keep those dependencies fixed.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.