Sub topic 3
Decorators in a nutshell
This chapter assumes you can define and call Python functions, including keyword arguments. It also assumes you know that functions are values that can be passed to other functions and returned from them. Later chapters use functools.wraps, cache, and lru_cache, which are all decorators or are used as decorators. So here we build a precise model of what the @ line does, when it runs, and where a hand-written decorator commonly goes wrong.
A decorator is a function that takes a function
A decorator is a callable that receives a function and returns a replacement for it. The replacement is usually a new function that calls the original and adds behavior before or after the call.
Here is a decorator written without any special syntax:
def shout(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
def greet(name):
return f"hello, {name}"
greet = shout(greet)
print(greet("ada")) # HELLO, ADAThere are three pieces:
shoutis the decorator. It takesfuncand returnswrapper.wrapperis a closure. It is an inner function that remembersfuncfrom the enclosing scope, even aftershouthas returned.- The line
greet = shout(greet)rebinds the namegreet. After it runs,greetrefers towrapper, and the original function is reachable only through the closure.
The @ syntax is shorthand for exactly that rebinding:
@shout
def greet(name):
return f"hello, {name}"
print(greet("ada")) # HELLO, ADAThis is equivalent to defining greet and then writing greet = shout(greet). Nothing else happens. The @ line is not special at call time. It is an ordinary function call that runs once.
Why wrapper takes `*args, **kwargs`
A decorator is usually written without knowing which function it will wrap. The wrapper must therefore accept whatever arguments the original accepts and pass them through unchanged. The signature (*args, **kwargs) does this. *args collects positional arguments into a tuple, and **kwargs collects keyword arguments into a dict. The call func(*args, **kwargs) unpacks them again.
A wrapper with a fixed signature works for only one shape of function:
def shout_one_arg(func):
def wrapper(name): # accepts exactly one argument
return func(name).upper()
return wrapper
@shout_one_arg
def join_words(first, second):
return f"{first} {second}"
# join_words("a", "b") raises TypeError: wrapper() takes 1 positional argument but 2 were givenThe error message names wrapper, not join_words. That is a hint about something covered shortly: once decorated, the name join_words refers to the wrapper.
When the decorator runs
The decorator runs at definition time, once. The wrapper runs at call time, every time. Confusing these two moments is the most common source of surprise.
def register(func):
print(f"decorating {func.__name__}")
return func
@register
def task():
print("running task")
print("definition finished")
task()
task()The output is:
decorating task
definition finished
running task
running taskThe message from register appears once, before the first call. This register decorator returns the original function, not a wrapper. That is legal, and it is a common pattern for recording functions in a registry such as a dict of command handlers. The decorator's return value only has to be something you want bound to the name.
If you put work in the decorator body but outside the wrapper, it runs at import time of the module. Setup that should happen on each call belongs inside the wrapper.
Doing something around the call
Most decorators add behavior before and after calling the original. Here is a timer:
import time
def timed(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.4f}s")
return result
return wrapper
@timed
def slow_sum(n):
return sum(range(n))
print(slow_sum(1_000_000))The printed time varies by machine, but the sum is 499999500000. Note the structure, because nearly every decorator follows it:
- Do something before the call (record the start time).
- Call the original and save its result.
- Do something after the call (print the elapsed time).
- Return the saved result.
A wrapper has to return the result explicitly, or callers receive None. That mistake is listed in the error table below.
Decorators that take arguments
Sometimes you want to configure a decorator, as in @repeat(times=3). In that case repeat(times=3) is a call that must itself return a decorator. You need three nested levels:
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
result = None
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(times=3)
def ping():
print("ping")
ping()This prints ping three times. The decoration step expands like this:
repeat(times=3)runs first and returnsdecorator, withtimescaptured in its closure.@decoratorthen applies toping, just like an ordinary decorator.
An outer function that produces a decorator is often called a decorator factory. functools.wraps, which you will meet in the next chapters, is used the same way. It is called with an argument (wraps(func)) and returns a decorator.
A related detail: partial from the first chapters of this tutorial can build such configured decorators too. The call partial(repeat, 3) returns a function that behaves like repeat(3). This is not required here, but it shows that decorators are ordinary callables and can be combined with other tools freely.
Stacking decorators
You can place several decorators on one function. They apply from the bottom up, nearest to the function first, so the top decorator ends up outermost.
def brackets(func):
def wrapper(*args, **kwargs):
return f"[{func(*args, **kwargs)}]"
return wrapper
def parens(func):
def wrapper(*args, **kwargs):
return f"({func(*args, **kwargs)})"
return wrapper
@brackets
@parens
def word():
return "hi"
print(word()) # [(hi)]This is equivalent to word = brackets(parens(word)). Swapping the two decorator lines changes the output to ([hi]). Order matters whenever decorators interact. For example, a logging decorator placed above a caching decorator logs every call, while one placed below it logs only the calls that miss the cache. The last chapters of this tutorial return to that case.
| Written as | Equivalent to | Outermost wrapper |
|---|---|---|
| `@a` then `@b` then `def f` | `f = a(b(f))` | `a` |
| `@b` then `@a` then `def f` | `f = b(a(f))` | `b` |
What the decorator hides
After decoration, the name refers to the wrapper, so the wrapper's own attributes show through. Check this with the shout decorator from the start of the chapter:
def shout(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs).upper()
return wrapper
@shout
def greet(name):
"""Return a greeting."""
return f"hello, {name}"
print(greet.__name__) # wrapper
print(greet.__doc__) # NoneThe function now reports itself as wrapper and has lost its docstring. Tracebacks, help(), and debugging tools all see the wrapper instead of greet. This is a real cost of writing decorators naively, and the following chapters fix it with functools.wraps. For now, keep in mind that a hand-written decorator replaces the function and does not modify it.
Common mistakes
Most decorator bugs come from a short list of causes. The table pairs each with its symptom.
| Mistake | What you see | Fix |
|---|---|---|
| Wrapper does not `return` the result | The decorated function always returns `None` | Save `result = func(...)` and `return result` |
| Decorator returns `wrapper()` instead of `wrapper` | The original runs at decoration time, and `TypeError` follows on the first call | Return the function object, with no parentheses |
| Decorator forgets to return anything | The name becomes `None`, and calls fail with `'NoneType' object is not callable` | End the decorator with `return wrapper` |
| Fixed wrapper signature | `TypeError` naming `wrapper()` when argument counts differ | Use `*args, **kwargs` |
| Factory used without parentheses, such as `@repeat` | The function is passed as `times`, and the first call fails with a missing argument | Write `@repeat(times=3)` |
| Setup placed outside the wrapper | Work happens once at import, not per call | Move per-call work inside `wrapper` |
The last row is not always a bug. Sometimes you want one-time setup, such as creating a lock or an empty dict that all calls share. Place it in the decorator body and the wrapper's closure keeps it. Be deliberate about which behavior you want.
A decorator holding state
Because the wrapper is a closure, it can carry state between calls. This counter keeps its count in a function attribute:
def count_calls(func):
def wrapper(*args, **kwargs):
wrapper.calls += 1
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
@count_calls
def hello():
return "hi"
hello()
hello()
print(hello.calls) # 2This works because hello is the wrapper, and calls is an attribute set on it. The cache decorators later in this tutorial use the same idea. They attach cache_info and cache_clear to the function they return, so you can call fib.cache_info() on a decorated function.
Each decorated function gets its own wrapper and therefore its own counter. Two functions decorated with count_calls do not share counts, since count_calls creates a new wrapper on every application.
Where this leads
You now have the model needed for the rest of the tutorial:
- A decorator is a function from function to function, applied once at definition time.
- The
@line is shorthand for rebinding a name to the decorator's return value. - The wrapper forwards
*args, **kwargsand must return the original result. - Decorators with arguments add an outer layer, and stacked decorators apply bottom-up.
- A naive wrapper replaces the function's name and docstring. The next chapter looks at that problem and its fix.
Exercise
Given the code below, what does it print, and why? Then say what you would change so that add(2, 3) prints 5.
def doubleresult(func):
def wrapper(args, kwargs):
func(args, *kwargs) 2
return wrapper
@doubleresult
def add(a, b):
return a + b
print(add(2, 3))
Show answer
It prints None. The wrapper computes func(args, kwargs) 2 but never returns it, so Python returns None by default. To get a result, write "return func(args, kwargs) 2". Note that this wrapper would then print 10, not 5, because it doubles the sum. To print 5 the decorator must not double the value, so the real change is to remove the doubling or to drop the decorator. The doubling is the decorator's purpose, so the correct fix for the missing return is "return func(args, kwargs) 2", which prints 10.
Exercise
Write a decorator factory called prefix(text) so that decorating a function that returns a string with @prefix(">> ") makes it return the original string with ">> " added at the front. Which nesting levels do you need?
Show answer
You need three levels: prefix(text) returns decorator, decorator(func) returns wrapper, and wrapper(args, kwargs) does the work. def prefix(text): def decorator(func): def wrapper(args, kwargs): return text + func(*args, kwargs) return wrapper return decorator @prefix(">> ") def hello(): return "hello" print(hello()) # >> hello
Exercise
A function is decorated as shown. In what order do the decorators apply to it, and which one's wrapper runs first when you call the function? @alpha @beta def work(): ...
Show answer
beta is applied first, because it is nearest to the function, so work = alpha(beta(work)). The wrapper created by alpha is outermost, so it runs first when work() is called. It then calls beta's wrapper, which calls the original function.