Decorators
A decorator is a function that wraps another function to add extra behaviour, such as logging, timing or checking permissions, without changing the original function's code. You apply one by writing @decorator_name above a function.
Functions are objects
Decorators rely on three facts about Python functions: you can store them in variables, pass them to other functions, and define them inside other functions.
def shout(text):
return text.upper() + "!"
yell = shout # store a function in a variable
print(yell("habari"))
def apply_twice(func, value): # pass a function as an argument
return func(func(value))
print(apply_twice(lambda x: x * 3, 2))
def make_multiplier(n): # return a function from a function
def multiply(x):
return x * n
return multiply
double = make_multiplier(2)
print(double(21))
The inner function multiply remembers n even after make_multiplier has finished. A function that remembers values from the place it was created is called a closure, and decorators are built from closures.
Your first decorator
A decorator takes a function, defines a new wrapper function that does something extra around it, and returns the wrapper.
def announce(func):
def wrapper():
print("About to run", func.__name__)
func()
print("Finished", func.__name__)
return wrapper
@announce
def greet():
print("Hello from Kuza Ndoto")
greet()
The @announce line is shorthand. It means exactly the same as writing greet = announce(greet) after the function definition. From then on, the name greet refers to the wrapper.
Decorating functions that take arguments
A useful decorator should work with any function, whatever its arguments and return value. Use *args and **kwargs to pass everything through, and return the original result.
import functools
def log_call(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with {args} {kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@log_call
def add(a, b):
"""Add two numbers."""
return a + b
add(3, 4)
add(2, b=10)
print(add.__name__, "-", add.__doc__)
@functools.wraps(func) copies the original function's name, docstring and other details onto the wrapper. Without it, add.__name__ would be "wrapper", which makes debugging and help() confusing. Always use it.
Forgetting return result in the wrapper. The decorated function then always returns None, even though the original returns a value. Another frequent slip is writing @log_call() with brackets for a decorator that doesn't take arguments.
A practical decorator: timing
import functools
import time
def timer(func):
@functools.wraps(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} seconds")
return result
return wrapper
@timer
def total_up_to(n):
return sum(range(n + 1))
print(total_up_to(1_000_000))
The timing depends on your computer, so your number will differ:
Decorators that take arguments
To write @repeat(3), you need one more layer: a function that takes the argument and returns a decorator.
import functools
def repeat(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def cheer(team):
print(f"Go {team}!")
cheer("Harambee Stars")
Stacking decorators
You can apply several decorators. The one closest to the function is applied first, so the outer one wraps everything.
def stars(func):
def wrapper():
return "**" + func() + "**"
return wrapper
def underscores(func):
def wrapper():
return "_" + func() + "_"
return wrapper
@stars
@underscores
def word():
return "kuza"
print(word()) # same as stars(underscores(word))()
Decorators you'll meet
| Decorator | What it does |
|---|---|
@property | Turns a method into an attribute-like value (Encapsulation) |
@classmethod, @staticmethod | Special kinds of methods (Methods & Attributes) |
@dataclass | Generates __init__, __repr__ and more for a class |
@functools.cache | Remembers results so repeated calls are instant |
@contextlib.contextmanager | Builds a context manager from a generator (Context Managers) |
@app.route("/") and similar | Web frameworks like Flask use decorators to connect URLs to functions |
functools.cache shows how powerful decorators can be. The slow recursive Fibonacci function becomes instant, because each value is calculated only once:
from functools import cache
@cache
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(80))
Without @cache, this recursive function would make trillions of calls and effectively never finish.
Key points
- A decorator is a function that takes a function and returns a new, wrapped function.
@decoabovedef fmeansf = deco(f).- Use
*args, **kwargs, return the result, and add@functools.wraps(func). - Decorators with arguments need an extra outer function.
Tip: use the ← and → keys to move between pages.
