Lesson · Functional Programming Tools
Decorators
55 min readDecorators
A decorator replaces a function or class with the result of another callable at definition time. Good decorators preserve metadata, keep control flow understandable, and make cross-cutting behavior explicit.
Learning goals
- Explain what
@traceddoes toaddat definition time, in terms of rebinding. - Trace one decorated call through the wrapper, the original function, and the returned value.
- Use
*argsand**kwargsin a wrapper and say why a fixed parameter list defeats a general decorator. - Say what
functools.wrapscopies and what breaks without it. - Write a decorator that takes an argument and identify the extra factory layer it needs.
Mental model
The rebinding happens at definition time, so every later call of add reaches the wrapper first, and the original function is reachable only through the closure the wrapper keeps.
Mental model
read it top to bottom
def add creates a function object ↓ @traced applies traced to it traced(add) returns wrapper ↓ the name add is rebound add now means wrapper, and wrapper calls the original
Core idea
A decorator is a function transformation applied where the function is defined: @traced rewrites the name add to whatever traced(add) returns. The wrapper closes over the original function, adds behavior around the call, and forwards the arguments unchanged. functools.wraps and the extra factory layer for argument-taking decorators exist to keep that replacement faithful and configurable.
Wrapping functions
A wrapper calls another function while adding behavior before, after, or around it. Preserve the wrapped function's contract and metadata unless the decorator intentionally changes the API.
@decorator
@name applies the named callable to the function defined directly below it and rebinds the function's name to the result. @traced above def add is the same as add = traced(add) after the def statement, so whatever the decorator returns becomes what every later call reaches.
Closures in decorators
A closure keeps references to names from an enclosing function scope after that outer call has returned. The captured binding, not a frozen snapshot of its value, is what matters.
functools.wraps
functools.wraps copies important metadata from a wrapped function to the wrapper and sets __wrapped__. It improves introspection, documentation, and decorator composition.
Decorators with arguments
A decorator that takes arguments is a factory: the argument call returns the real decorator, which then receives the function. @repeat(3) evaluates repeat(3) first and applies the returned decorator to the function, which is why the definition needs one more nested layer.
Class decorators overview
A class decorator receives a class object and returns whatever should replace it: usually the same class after adding or changing attributes, sometimes a different object. @dataclass is the standard-library example; the mechanism matches function decorators, only the target is a class.
Walkthrough
@wraps(fn)decorateswrapperbeforewrapperis returned, so the wrapper carries the metadata ofadd(its__name__, docstring, and so on) rather than its own.def wrapper(*args, **kwargs)accepts any call shape and forwards it unchanged; a fixed signature like(a, b)would only fit functions that take exactly those two arguments.- When
add(2, 3)runs, Python actually callswrapper(2, 3), because@tracedrebound the name. The wrapper prints its line, calls the capturedfn(2, 3)(the original function), and returns its5untouched. - Predict before running: what text appears before
5, and whatadd.__name__reports.
Experiments to try
- Print
add.__name__andadd.__wrapped__after the definition; then remove@wraps(fn)and compare both values. - Add a second decorated function
mul(a, b), call it with three arguments, and read theTypeError; explain which function rejected the call. - Write
@repeat(n)as an argument-taking decorator that calls the wrapped functionntimes and returns the last result; count the layers of nesting. - Convert
@tracedinto@logged(label)that prints the label instead of the function name; state which objectlogged("add")returns and when it runs.
Common mistakes
- Omitting
functools.wraps, so the rebound name carries the wrapper's identity and tools that read__name__or show help describe the wrong function. - Writing the wrapper's parameter list for one function (
(a, b)) and breaking the decorator for every other call shape;*args, **kwargskeeps it general. - Calling the decorated function inside the decorator body instead of inside the wrapper; the call then runs once at definition time and its result replaces the function.
- Forgetting the extra nesting for an argument-taking decorator:
@repeatused withrepeat(3)misreads3as the function, and the error message talks about calling anint.
Practice: Easy
- Run the worked example, then print
add(2, 3)together withadd.__name__; temporarily remove@wraps(fn)and compare the printed names. - Change the wrapper's print to show
args; calladd(2, 3)and record the tuple the wrapper received. - Apply
@tracedto a function with no arguments and confirm the same wrapper fits; name the language feature that makes both calls work.
Practice: Medium
- Write
@suppress_errorsthat catchesValueErrorfrom the wrapped function and returnsNone; state the new contract and one caller-visible consequence. - Write
@count_callsthat keeps a counter in a closure, expose it as an attribute of the wrapper, and show the count after three calls. - Apply
@tracedto a method of a small class and check howselfarrives inargs; explain why no special handling was needed.
Practice: Hard
- Build
@validated(schema)whereschemamaps argument names to predicate callables; reject bad calls withValueErrorand define what happens when a caller passes an argument the schema does not mention. - Implement
@memoizeon top offunctools.wrapsthat caches results in a dictionary cell; comparefib(30)with and without it and state the cache key. - Design an ordering test for stacked decorators: apply
@tracedand a timing decorator to the same function in both orders, predict each print order from the rebinding rule, then run and explain the result.
Lesson checklist
- I can rewrite
@tracedasadd = traced(add)and explain the equivalence. - I can trace one decorated call through the wrapper, the original function, and the return value.
- I can say what
functools.wrapspreserves and what breaks without it. - I can write an argument-taking decorator and identify the three nested functions it needs.
Remember
A decorator runs at definition time and rebinds a name to whatever it returns, which is usually a wrapper closed over the original function. The wrapper adds behavior around the call and forwards the arguments; `functools.wraps` keeps the replacement transparent to tools. Argument-taking decorators are the same mechanism with one extra factory layer.
Interview angles
What is the main purpose of **Wrapping functions**?+
A wrapper calls another function while adding behavior before, after, or around it. Preserve the wrapped function's contract and metadata unless the decorator intentionally changes the API.
What should you pay attention to when using **@decorator**?+
@name applies the named callable to the function defined directly below it and rebinds the function's name to the result. @traced above def add is the same as add = traced(add) after the def statement, so whatever the decorator returns becomes what every later call reaches.
How does **Closures in decorators** fit into this lesson?+
A closure keeps references to names from an enclosing function scope after that outer call has returned. The captured binding, not a frozen snapshot of its value, is what matters.
What goes wrong when a wrapper skips `functools.wraps`?+
The wrapper keeps its own __name__, __doc__, and __module__, so help() and any tool that dispatches on those attributes describes the wrapper instead of the wrapped function. functools.wraps copies them across and sets __wrapped__.