Python Decorators
A decorator wraps a function to add behaviour — logging, timing, caching, access checks — without changing the function's own code. You've already met a few: @property, @classmethod, @dataclass and @lru_cache. This lesson shows how they work and how to write your own.
The building blocks
Decorators rely on two facts you've seen before:
- Functions are objects: you can pass them to other functions and return them.
- An inner function can remember variables from the function that created it (a closure).
def shout(func):
def wrapper():
return func().upper() + "!"
return wrapper
def greet():
return "hello"
loud_greet = shout(greet) # wrap greet by hand
print(greet())
print(loud_greet())hello
HELLO!
shout takes a function and returns a new function that calls the original and modifies its result. That's a decorator.
The @ syntax
Writing @shout above a definition is shorthand for greet = shout(greet):
def shout(func):
def wrapper():
return func().upper() + "!"
return wrapper
@shout
def greet():
return "good morning"
print(greet())GOOD MORNING!
Handling any arguments
A real decorator shouldn't care what arguments the wrapped function takes. Use *args and **kwargs to pass everything through, and functools.wraps to keep the original function's name and docstring:
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
arg_text = ", ".join([repr(a) for a in args] + [f"{k}={v!r}" for k, v in kwargs.items()])
print(f"-> {func.__name__}({arg_text})")
result = func(*args, **kwargs)
print(f"<- {func.__name__} returned {result!r}")
return result
return wrapper
@log_calls
def add(a, b):
"""Add two numbers."""
return a + b
@log_calls
def greet(name, punctuation="!"):
return f"Hi {name}{punctuation}"
add(2, 3)
greet("Tam", punctuation="?")
print(add.__name__, "-", add.__doc__)-> add(2, 3)
<- add returned 5
-> greet('Tam', punctuation='?')
<- greet returned 'Hi Tam?'
add - Add two numbers.
Without @functools.wraps, add.__name__ would be "wrapper", which makes debugging confusing.
Decorators that take arguments
To configure a decorator — @repeat(3) — add one more layer: a function that receives the settings and returns a decorator:
import functools
def repeat(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
results = []
for _ in range(times):
results.append(func(*args, **kwargs))
return results
return wrapper
return decorator
@repeat(3)
def roll_call(name):
return f"{name} present"
print(roll_call("Phong"))['Phong present', 'Phong present', 'Phong present']
Practical examples
Counting calls and caching
A decorator can keep state, for example on the wrapper function itself. Here's a tiny version of functools.lru_cache:
import functools
def memoize(func):
cache = {}
@functools.wraps(func)
def wrapper(n):
if n not in cache:
cache[n] = func(n)
return cache[n]
wrapper.cache = cache
return wrapper
@memoize
def slow_square(n):
print(f" computing {n}^2")
return n * n
print(slow_square(4))
print(slow_square(4)) # served from the cache
print(slow_square(5))
print(sorted(slow_square.cache)) computing 4^2
16
16
computing 5^2
25
[4, 5]
Validating input
import functools
def require_positive(func):
@functools.wraps(func)
def wrapper(*args):
if any(a <= 0 for a in args):
raise ValueError(f"{func.__name__} needs positive numbers, got {args}")
return func(*args)
return wrapper
@require_positive
def rectangle_area(w, h):
return w * h
print(rectangle_area(3, 4))
try:
rectangle_area(3, -1)
except ValueError as err:
print("ValueError:", err)12
ValueError: rectangle_area needs positive numbers, got (3, -1)
Stacking decorators
Several decorators can be applied to one function. They're applied bottom-up (closest to the def first), so the top one is the outermost wrapper:
@log_calls
@require_positive
def rectangle_area(w, h): ...
# same as: rectangle_area = log_calls(require_positive(rectangle_area))Built-in and standard-library decorators
| Decorator | Purpose |
|---|---|
@property |
method accessed like an attribute |
@classmethod, @staticmethod |
alternative method kinds |
@functools.lru_cache / @functools.cache |
memoise results |
@functools.wraps |
copy metadata onto a wrapper |
@dataclasses.dataclass |
generate boilerplate for a class |
@contextlib.contextmanager |
build a context manager from a generator |
Tip: Decorators are best for cross-cutting concerns — things many functions need, like logging or permissions. If only one function needs the behaviour, just put it in that function.
Test yourself
What is @my_deco above def f(): ... equivalent to?
- f = my_deco
- f = my_deco(f)
- my_deco = f(my_deco)
- f(my_deco)
Why use functools.wraps inside a decorator?
- To make the wrapper faster
- To keep the original function's name and docstring on the wrapper
- To allow arguments
- It's required for the @ syntax
With stacked decorators @a on top of @b, which is applied first?
- a
- b
- Both at the same time
- It depends on the function