Sub topic 13
Decorators as higher-order functions
This chapter assumes you can write closures, you know *args and **kwargs, and you know that a function is a value you can pass around. A decorator is a higher-order function that takes a function and returns a function. Once you see it that way, the @ syntax is just shorthand.
What a decorator is
The @ line above a def is shorthand for a reassignment. These two definitions of add end up in the same state:
from functools import wraps
def log_calls(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_calls
def add(a, b):
return a + b
def sub(a, b):
return a - b
sub = log_calls(sub)
print(add(2, 3))
print(sub(5, 1))
# calling add
# 5
# calling sub
# 4log_calls receives the original function, builds a new function called wrapper, and returns it. The name add is then bound to wrapper. The original function survives only inside the closure, as the variable func.
Two timing points matter in this flow:
- The decorator runs once, when the
defstatement executes. Usually that is at import time. - The wrapper runs every time the decorated name is called.
Code placed in the outer function therefore runs once. Code placed in the wrapper runs on every call.
Why the wrapper takes `*args, **kwargs`
The wrapper does not know which function it will wrap. Accepting *args, **kwargs and forwarding them unchanged lets one decorator work with any signature. Forgetting to return the result of func(...) is a common error. The decorated function then silently returns None.
Why `functools.wraps` matters
A wrapper replaces the original function, so introspection sees the wrapper unless you copy the metadata over. Compare these two versions:
from functools import wraps
def noisy(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def polite(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@noisy
def greet(name):
"""Return a greeting."""
return f"hello {name}"
@polite
def greet2(name):
"""Return a greeting."""
return f"hello {name}"
print(greet.__name__, greet.__doc__) # wrapper None
print(greet2.__name__, greet2.__doc__) # greet2 Return a greeting.
print(greet2.__wrapped__("Ada")) # hello Adawraps is itself a decorator factory, which this chapter covers below. It copies __name__, __doc__, __module__ and a few other attributes. It also sets __wrapped__, which points to the original function. Debuggers, help(), inspect.signature and test tools all rely on this metadata.
Decorators that return the same function
A decorator does not have to wrap anything. It may do some work and return the original function unchanged. A registry is the classic example:
handlers = {}
def register(name):
def decorator(func):
handlers[name] = func
return func
return decorator
@register("greet")
def greet(who):
return f"hello {who}"
@register("shout")
def shout(who):
return f"HELLO {who.upper()}"
for key, fn in handlers.items():
print(key, fn("ada"))
# greet hello ada
# shout HELLO ADAWeb frameworks use this pattern to attach a function to a URL or an event name. Calls to greet are not slowed down, because no wrapper exists.
Any expression that produces a callable can follow @ in Python 3.9 and later. A lambda in parentheses works, for example @(lambda f: f). Lambdas are rarely a good fit here, though. A decorator usually needs an inner def, and a lambda cannot contain statements.
Decorators with arguments
register("greet") above has three layers. A decorator that takes its own arguments is really a function that returns a decorator:
from functools import wraps
def repeat(times):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
result = None
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def say(msg):
print(msg)
say("hi")
# hi
# hi
# hiThe line @repeat(3) first evaluates repeat(3), which returns decorator. Python then applies decorator to say. This is the same closure and function-factory pattern from earlier chapters, with one more level.
The layers are:
repeat(times)captures the configuration.decorator(func)captures the function.wrapper(*args, **kwargs)runs on each call.
A common error is writing @repeat without the parentheses. Python then passes say in as times. The result is a repeat call that returns decorator instead of a wrapped say, so say("hi") ends up calling decorator("hi"). The error appears at the first call, far from the cause.
Stacking decorators
You can put several decorators on one function. They apply from the bottom up, so the one closest to the def wraps first:
from functools import wraps
def tag(name):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
return f"<{name}>{func(*args, **kwargs)}</{name}>"
return wrapper
return decorator
@tag("b")
@tag("i")
def text(s):
return s
print(text("hi")) # <b><i>hi</i></b>This is equivalent to text = tag("b")(tag("i")(text)). The outer decorator's wrapper runs first on a call, and it calls the inner wrapper. Order matters whenever the decorators interact. For example, a caching decorator placed above a logging decorator skips the logging on cache hits. Placed below it, the cache sits inside the logging, so every call is logged.
Decorators with state
A wrapper is a function, and functions can carry attributes. A closure variable declared with nonlocal also works. Here is a call counter that uses an attribute:
from functools import wraps
def count_calls(func):
@wraps(func)
def wrapper(*args, **kwargs):
wrapper.calls += 1
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
@count_calls
def ping():
return "pong"
ping()
ping()
print(ping.calls) # 2The state lives on the wrapper, so each decorated function gets its own counter. State stored this way is shared across all callers and is not thread-safe. Two threads incrementing calls can lose updates.
A timing decorator
Here is a small, practical decorator. It measures how long a call takes and prints the result in milliseconds:
import time
from functools import wraps
def timed(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
elapsed = (time.perf_counter() - start) * 1000
print(f"{func.__name__} took {elapsed:.2f} ms")
return wrapper
@timed
def total(n):
return sum(range(n))
print(total(1_000_000))The try/finally makes the timing line print even if func raises an exception. The exception still propagates to the caller. The exact time in the output varies from run to run.
Decorators in the standard library
You have been using decorators from functools throughout this tutorial. functools.cache and functools.lru_cache are the ones most often used:
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80)) # 23416728348467685
print(fib.cache_info().hits > 0) # TrueWithout the cache, the recursive version makes an enormous number of calls. With it, each value is computed once. Cached arguments must be hashable, because the cache is a dictionary keyed by the arguments.
Gotchas and failure modes
| Problem | Cause | Fix |
|---|---|---|
| Decorated function returns `None` | The wrapper calls `func(...)` without `return` | Return the result |
| `help(f)` shows `wrapper` | Metadata not copied | Add `@wraps(func)` |
| `TypeError` at the first call | `@repeat` used without `(3)` | Write `@repeat(3)` |
| Cache or counter shared unexpectedly | State kept in a module-level or closure variable | Store state per decorated function |
| Method decorator breaks | Wrapper assumes a fixed argument list | Accept `*args, **kwargs` and forward `self` unchanged |
| Surprising behavior when stacked | Order of application not considered | Read decorators from the bottom up |
Decorator or plain higher-order function?
A decorator is only a convenient spelling for f = wrapper_maker(f). Choose it when the behavior belongs to the function permanently, such as caching, logging, access checks or registration. Pass a function as an argument instead when the caller picks the behavior for a single use, as with sorted(items, key=...). Both are higher-order functions. A decorator returns a function, and a key function is passed in.
Exercise
In @repeat(2) followed by @tag("b") on a function f (so repeat is the outer decorator and tag is the inner one), which is applied to f first, and what does repeat(2) return before it is applied?
Show answer
Decorators apply from the bottom up, so tag("b") is applied to f first. The expression repeat(2) is evaluated on its own and returns a decorator function. That decorator is then applied to the tagged function, producing the final wrapper.
Exercise
Write a decorator retry(times) that calls the wrapped function up to times times. If the function raises an exception, it tries again. If the last attempt also raises, the exception propagates. Which three function layers does it need, and where does @wraps go?
Show answer
It needs three layers: retry(times) returns decorator(func), which returns wrapper(*args, **kwargs). Put @wraps(func) on wrapper. Inside the wrapper, loop over range(times), and in each attempt return func(*args, **kwargs) inside a try. Catch Exception on every attempt except the last, and let the last attempt raise by re-raising or by calling func outside the try.
Exercise
A function decorated with a hand-written decorator prints wrapper from f.__name__. What is missing, and how can you reach the original function afterwards?
Show answer
The wrapper lacks @functools.wraps(func). Once wraps is added, f.__name__ is correct and f.__wrapped__ refers to the original undecorated function.