← All lessons
Python advanced · Lesson 7 of 11

Decorators

A decorator is a function that takes a function and returns a new one, usually a wrapper that does something before or after calling the original. It's how you add logging, timing, caching, checks or retries to many functions without changing their code. You've already used two: @cache and @dataclass.

Here's one written by hand. wrapper accepts any arguments (*args, **kwargs), passes them on to the original, and adds a line of output around it:

def announce(fn):
    def wrapper(*args, **kwargs):
        print(f"calling {fn.__name__}")
        result = fn(*args, **kwargs)
        print(f"{fn.__name__} returned {result}")
        return result
    return wrapper

def add(a, b):
    return a + b

add = announce(add)
add(2, 3)
Prints
calling add
add returned 5

add = announce(add) replaces add with the wrapped version. The @ line is just shorthand for that: writing @announce above a def does exactly the same thing, at the moment the function is defined.

def announce(fn):
    def wrapper(*args, **kwargs):
        print(f"calling {fn.__name__}")
        return fn(*args, **kwargs)
    return wrapper

@announce
def greet(name):
    return f"hi {name}"

print(greet("Ana"))
Prints
calling greet
hi Ana

One problem: the wrapped function now reports itself as wrapper, losing its name and docstring, which confuses debuggers and documentation tools. functools.wraps copies them over. Put it on every wrapper you write.

import functools

def logged(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        return fn(*args, **kwargs)
    return wrapper

@logged
def tidy(s):
    """Strip and lower-case s."""
    return s.strip().lower()

print(tidy.__name__, "|", tidy.__doc__)
Prints
tidy | Strip and lower-case s.

A decorator that takes options, like @retry(times=3), needs one more layer: retry(times=3) is called first and must return the actual decorator. So it's a function that returns a decorator that returns a wrapper.

import functools

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

calls = {"n": 0}

@retry(times=3)
def flaky():
    calls["n"] += 1
    if calls["n"] < 3:
        raise ConnectionError("no network")
    return "ok"

print(flaky())
Prints
attempt 1 failed
attempt 2 failed
ok

Decorators stack: the one nearest the def is applied first. Frameworks lean on them heavily, for example @app.get("/items") in web frameworks registers a function as the handler for a web address. Classes can be decorated too, which is what @dataclass does. Built-in decorators you'll meet in classes are @property (a method read like an attribute, obj.area with no brackets), @staticmethod and @classmethod.

class Circle:
    def __init__(self, r):
        self.r = r

    @property
    def area(self):
        return round(3.14159 * self.r ** 2, 2)

    @classmethod
    def unit(cls):
        return cls(1)

print(Circle(2).area, Circle.unit().r)
Prints
12.57 1

Practice

What does this print?

def twice(fn):
    def wrapper(x):
        return fn(fn(x))
    return wrapper

@twice
def add3(x):
    return x + 3

print(add3(10))
More info

Quick reference

decoratorA function that takes a function and returns a replacement (usually a wrapper).
@deco above def fShorthand for f = deco(f).
@functools.wraps(fn)Keeps the original's name and docstring on the wrapper.
@deco(option)deco(option) is called first and must return the decorator.
@property / @classmethod / @staticmethodRead a method like an attribute / gets the class / gets neither.

Related courses