Learn / Intermediate / Lesson 7

Decorators

13 min Tested on Python 3.15Updated By
In short

A decorator is a function that takes another function and returns an improved version of it. Writing @timer above def work(): is short for work = timer(work). Decorators add behaviour such as logging, timing, retries or caching without touching the function's own code.

Step 1: functions inside functions

Python
def make_multiplier(factor: int):
    def multiply(x: int) -> int:
        return x * factor      # remembers factor
    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)
print(double(10), triple(10))
Output
20 30

The inner function remembers factor even after make_multiplier has finished. That's called a closure, and it's the engine behind every decorator.

Step 2: a function that wraps a function

Python
def shout(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return result.upper()
    return wrapper

def greet(name: str) -> str:
    return f"hello, {name}"

loud_greet = shout(greet)
print(loud_greet("ana"))
Output
HELLO, ANA

Step 3: the @ syntax

Python
import functools

def shout(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs).upper()
    return wrapper

@shout
def greet(name: str) -> str:
    """Greet someone."""
    return f"hello, {name}"

print(greet("ben"))
print(greet.__name__, "-", greet.__doc__)
Output
HELLO, BEN
greet - Greet someone.

A practical decorator: timing

Python
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:.3f}s")
        return result
    return wrapper

@timer
def total(n: int) -> int:
    return sum(range(n))

result = total(2_000_000)
print(result)

Decorators with arguments

Python
import functools

def retry(times: int):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except ConnectionError as err:
                    print(f"Attempt {attempt} failed: {err}")
            raise ConnectionError(f"gave up after {times} attempts")
        return wrapper
    return decorator

calls = 0

@retry(times=3)
def fetch() -> str:
    global calls
    calls += 1
    if calls < 3:
        raise ConnectionError("server busy")
    return "data received"

print(fetch())
Output
Attempt 1 failed: server busy
Attempt 2 failed: server busy
data received

A decorator with arguments needs one extra layer: retry(times=3) returns the actual decorator, which then wraps the function.

Built-in decorators you'll use

Python
from functools import cache

@cache
def fib(n: int) -> int:
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(80))
print(fib.cache_info().hits > 0)
Output
23416728348467685
True
  • @functools.cache and @lru_cache remember results of expensive calls.
  • @property, @staticmethod and @classmethod shape methods in classes.
  • @dataclass writes class boilerplate.
  • Web frameworks use decorators for routes, e.g. @app.get("/items") in FastAPI.

Practice

Write a decorator log_call that prints Calling NAME before running the function (use func.__name__) and then returns the function's result. Decorate def add(a, b): return a + b with it and print add(2, 3).

Expected output:
Calling add
5
Your code

Quick check

1. @timer above def work(): is the same as...

2. Why use *args, **kwargs in a wrapper?

3. What does @functools.cache do?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →