Sub topic 3
Decorators in a nutshell
This chapter covers what a decorator is and how one is built. It assumes you can define and call Python functions, pass functions around as values, and have seen the @ symbol before. The next chapter shows what a simple decorator breaks, and the chapter after that fixes it with functools.wraps.
What a decorator does
A decorator is a callable that takes a function and returns a replacement for it. The @ line is shorthand for reassigning the name.
def shout(func):
def wrapper():
return func().upper()
return wrapper
def hello():
return "hello"
hello = shout(hello)
print(hello()) # HELLOThe same thing with @ syntax:
def shout(func):
def wrapper():
return func().upper()
return wrapper
@shout
def hello():
return "hello"
print(hello()) # HELLOBoth versions do the same work. Python defines hello, passes it to shout, and binds the name hello to whatever shout returns. After that, hello is no longer your original function. It is wrapper.
The standard shape
Most decorators follow one pattern: an outer function that receives the function, and an inner function that wraps it.
def log_calls(func):
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
result = func(*args, **kwargs)
return result
return wrapper
@log_calls
def add(a, b):
return a + b
print(add(2, 3))Output:
calling add
5Three details matter here.
- The inner function takes
*argsand**kwargs, so it accepts any call that the original accepts. - The inner function returns the original result. If you forget the
return, the decorated function silently returnsNone. - The outer function returns
wrapperitself, without calling it. Writingreturn wrapper()is a common slip.
func stays available inside wrapper because the inner function is a closure. A closure is a function that keeps access to variables from the scope where it was defined.
flowchart TDOrder of events
A decorator runs once, at definition time. The wrapper it returns runs on every call. This difference explains many surprises.
def announce(func):
print(f"decorating {func.__name__}")
def wrapper(*args, **kwargs):
print(f"running {func.__name__}")
return func(*args, **kwargs)
return wrapper
@announce
def work():
return 1
print("defined")
work()
work()Output:
decorating work
defined
running work
running work"decorating work" prints once, before the first call. "running work" prints on each call.
Decorators that take arguments
Sometimes a decorator needs its own settings. Add one more layer: a function that takes the settings and returns the real decorator.
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()repeat(times=3) runs first and returns decorator. Then @ applies decorator to ping. This gives three layers: settings, function, call.
Stacking decorators
You can place several decorators on one function. They apply from the bottom up, so the one closest to the function wraps it first.
@outer
@inner
def f():
...This equals f = outer(inner(f)). On a call, outer's wrapper runs first and inner's wrapper runs inside it. The order matters whenever one decorator changes what the other sees. A later chapter combines a logging decorator with functools.cache and shows this effect.
Common errors
| Symptom | Likely cause |
|---|---|
| Decorated function returns `None` | The wrapper does not `return func(...)` |
| `TypeError: 'function' object is not callable` after decoration | The outer function returned `wrapper()` instead of `wrapper` |
| `TypeError` about missing arguments when using `@repeat(3)` style | The decorator was written without the extra settings layer, or used without parentheses |
| Wrapper rejects some calls | The wrapper has fixed parameters instead of `*args, **kwargs` |
Why this leads to a problem
After decoration, the name add refers to wrapper. Ask it for its name and it answers with the wrapper's name, not add. The next chapter looks at that closely.
Exercise
Write a decorator double_result that multiplies the return value of any function by 2. Apply it to def one(): return 1 and say what one() returns. Then say in what order the prints appear if the decorator body itself contains a print("decorating") outside the wrapper and one is called twice.
Show answer
def doubleresult(func): def wrapper(args, kwargs): return func(args, *kwargs) 2 return wrapper @doubleresult def one(): return 1 one() returns 2. A print placed in the decorator body (outside wrapper) runs once, when the function is defined, so "decorating" appears one time, before either call. Calls to one() do not print it again.