← Learning Hub
Advanced

Decorators

Functions in Python are values: you can pass them around and return them. A decorator is a function that takes a function and returns a new one with extra behaviour - like logging, timing or checking.

Sometimes you want to add the same extra behaviour to many functions: log every call, measure how long it takes, check that the user is logged in, retry when the network fails. Copying that code into every function would be messy. A decorator wraps a function with the extra behaviour, and you apply it with one line: @decorator_name. Web frameworks like Flask and FastAPI use decorators everywhere.

Example
You can edit this code.

@shout above the function is a short way of writing greet = shout(greet).

A timing decorator

Example
import time
from functools import wraps

def timed(func):
    @wraps(func)                     # keeps the original name and docstring
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        ms = (time.perf_counter() - start) * 1000
        print(f"{func.__name__} took {ms:.1f} ms")
        return result
    return wrapper

@timed
def total(n):
    return sum(range(n))

total(1_000_000)   # prints something like: total took 12.3 ms

Decorators with settings

Example
You can edit this code.

Built-in decorators you'll see

  • @property - a method you read like a value (order.total)
  • @staticmethod, @classmethod - methods that don't need an object
  • @functools.cache - remember results of slow calls
  • @app.route("/") in Flask, @app.get("/") in FastAPI - connect web addresses to functions
Key points
  • A decorator takes a function and returns a wrapped version.
  • @name above a def applies it.
  • Use functools.wraps to keep the original name and docs.
  • Built-ins: @property, @staticmethod, @classmethod, @cache.

📝 Test yourself

1. @shout above def greet means...
2. Why use @wraps(func) inside a decorator?
3. Fill in the built-in decorator that makes a method readable like a value:
@ def total(self): ...