Stop 08 · Intermediate PythonTopics · 4/10

Decorators

Part of the Python Roadmap

In short

Need to time ten functions, log every API call or check login before certain views? Decorators add that behaviour with one line above each function, and you'll see them everywhere in Flask, FastAPI and Django.

A decorator is a function that wraps another function to add behaviour, such as timing, logging or access checks, without changing its code. The @decorator line above a function applies it, and functools.wraps keeps the original name.

The jaadu wraps a small box in shiny paper and ties a big ribbon on top, adding a little tag on the side.

Think of it like this

Gift wrapping

The present inside doesn't change, but wrapping it adds a ribbon and a card. A decorator wraps your function: the original still does its job, and the wrapper adds something before and after, like timing or logging, without you opening the box.

Watch it happen

Calling a decorated function

Caller
wrapper
original

fetch_rates()

1/5The name fetch_rates now points to the wrapper, so the wrapper runs first.

The big ideas

What you need to know

A function that wraps

A decorator takes a function, defines a wrapper around it, and returns the wrapper.

@ is shorthand

@timer above def f is exactly the same as writing f = timer(f) after it.

*args, **kwargs

The wrapper accepts any arguments and passes them through, so one decorator works on any function.

functools.wraps

@wraps(func) on the wrapper keeps the original name and docstring, which matters for debugging and frameworks.

See it in code

Walk through the code

python
1import time2from functools import wraps3 4def timer(func):5    @wraps(func)6    def wrapper(*args, **kwargs):7        start = time.perf_counter()8        result = func(*args, **kwargs)9        print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")10        return result11    return wrapper12 13def retry(times: int):14    def decorator(func):15        @wraps(func)16        def wrapper(*args, **kwargs):17            for attempt in range(1, times + 1):18                try:19                    return func(*args, **kwargs)20                except ConnectionError:21                    print(f"Attempt {attempt} failed")22            raise ConnectionError(f"Gave up after {times} tries")23        return wrapper24    return decorator25 26@timer27def total_sales(amounts: list[float]) -> float:28    return sum(amounts)29 30@retry(times=3)31def fetch_rates() -> dict[str, float]:32    return {"USD": 83.2}33 34print(total_sales([1200, 450, 999]))35print(fetch_rates())36print(total_sales.__name__)     # total_sales, thanks to @wraps

1/7timer receives a function and builds a wrapper around it. @wraps copies the original's name.

A timing decorator, a decorator that takes arguments (retry), and both applied with @.

Save yourself the pain

Common mistakes

Oops

Forgetting return result in the wrapper, so the decorated function always returns None.

Do this instead

Always return what the original function returned.

Oops

Writing the wrapper as def wrapper(): and breaking every function that takes arguments.

Do this instead

Use def wrapper(*args, **kwargs) and pass both through.

Oops

Skipping @wraps(func), so every function shows up as 'wrapper' in logs.

Do this instead

Decorate the wrapper with @functools.wraps(func).

Your mission

Login-required decorator

~25 min

Quick check

@timer placed above def report(): is equivalent to which line?

Go deeper

  1. 1Write a @timer decorator that prints how long a function took.
  2. 2Use functools.wraps inside your decorator.
  3. 3Read how Flask's @app.route or pytest's @pytest.fixture use decorators.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge