Python Functions · Lesson 73 of 149

Python Decorators

What you will learn

  • What a decorator is, and what the @ syntax means
  • How to write a wrapper that accepts any arguments
  • Why to use functools.wraps
  • Decorators with arguments, and stacking decorators
  • Practical decorators: logging, timing, retry, registry, caching
  • The built-in lru_cache

1. The idea

A decorator is a function that takes a function, adds something to it, and returns the improved function. It lets you add behaviour (logging, timing, checking, caching) without changing the original function's code. It uses everything from this chapter: functions as values (lesson 11.7), *args and **kwargs (lesson 11.4) and closures (lesson 11.10).

Here is a decorator that makes a function's text result upper case:

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

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

greet = shout(greet)
print(greet("rina"))
HELLO, RINA
  • shout takes the function greet.
  • It builds a new function, wrapper, which calls the original and changes its result.
  • greet = shout(greet) replaces the name greet with the wrapped version.
Quick check: after `greet = shout(greet)`, which function does the name `greet` refer to?

The wrapper, which calls the original greet inside.

2. The @ syntax

Writing greet = shout(greet) after the function is easy to miss. The @decorator line above the def does exactly the same thing:

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

print(greet("rina"))
HELLO, RINA

@shout above def greet means greet = shout(greet), applied as soon as the function is defined. There is no bracket and no argument after @shout: it names the decorator.

3. The wrapper: accept anything, pass everything on

A decorator should work for any function, whatever its parameters. So the wrapper takes *args, **kwargs and passes them on (lesson 11.4). It also returns whatever the original returned:

def log_calls(func):
    def wrapper(*args, **kwargs):
        shown = [repr(a) for a in args] + [f"{k}={v!r}" for k, v in kwargs.items()]
        result = func(*args, **kwargs)
        print(f"{func.__name__}({', '.join(shown)}) -> {result!r}")
        return result
    return wrapper

@log_calls
def add(a, b=0):
    return a + b

add(1, 2)
add(5)
add(a=3, b=4)
add(1, 2) -> 3
add(5) -> 5
add(a=3, b=4) -> 7

Common mistakes in a wrapper: forgetting to return the result (the decorated function then returns None), and forgetting *args, **kwargs (then it breaks for functions with other parameters).

4. The problem of lost identity, and functools.wraps

The wrapper replaces the function, so the function's name and docstring are lost:

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

print(greet.__name__)
print(greet.__doc__)
wrapper
None

help(greet) and error messages would now talk about wrapper. The fix is the decorator functools.wraps, applied to the wrapper. It copies the name, docstring and other details from the original, and also stores the original as __wrapped__:

import functools

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

@shout2
def greet2(name):
    """Greet someone."""
    return f"hello, {name}"

print(greet2("rina"))
print(greet2.__name__)
print(greet2.__doc__)
print(greet2.__wrapped__("x"))
HELLO, RINA
greet2
Greet someone.
hello, x

@functools.wraps(func) on the inner wrapper is the standard habit. Always include it. (Note that it is itself a decorator with an argument, which section 6 explains.)

5. Decorators that keep data

Because the wrapper is a closure, it can remember things between calls. A function is an object, so it can also carry attributes:

def count_calls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        wrapper.calls += 1
        return func(*args, **kwargs)
    wrapper.calls = 0
    return wrapper

@count_calls
def hello():
    return "hi"

hello()
hello()
hello()
print(hello.calls)
3

A timer is another favourite. It measures how long a call takes with time.perf_counter():

import time

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        wrapper.last = time.perf_counter() - start
        return result
    return wrapper

@timer
def slow():
    time.sleep(0.02)
    return "done"

print(slow())
print(slow.last >= 0.02, slow.last < 0.5)
done
True True

(The exact time varies, so the test checks only that it is between 0.02 and 0.5 seconds. Lesson 18.5 covers timing properly.)

6. Decorators with arguments

Sometimes you want to configure the decorator, such as @repeat(3). The trick is one more layer: a function that takes the setting and returns the real decorator:

def repeat(times):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            return [func(*args, **kwargs) for _ in range(times)]
        return wrapper
    return decorator

@repeat(3)
def roll():
    return 4

print(roll())
print(roll.__name__)

@repeat(times=2)
def say(x):
    return x

print(say("hi"))
[4, 4, 4]
roll
['hi', 'hi']

Follow the layers:

  1. repeat(3) runs first and returns the function decorator (which remembers times = 3).
  2. @ then applies that to roll: roll = decorator(roll).
  3. Calling roll() calls wrapper, which calls the original three times.

So there are three nested functions: the outer one takes the settings, the middle one takes the function, and the inner one takes the call's arguments.

7. Stacking decorators

You can put several decorators on one function. They are applied from the bottom up: the one closest to the def first:

def bold(f):
    @functools.wraps(f)
    def w(*a, **k):
        return "<b>" + f(*a, **k) + "</b>"
    return w

def italic(f):
    @functools.wraps(f)
    def w(*a, **k):
        return "<i>" + f(*a, **k) + "</i>"
    return w

@bold
@italic
def text():
    return "hi"

print(text())
<b><i>hi</i></b>

@bold above @italic means text = bold(italic(text)): italic wraps the function first, and bold wraps the result. Swapping the two lines gives <i><b>hi</b></i>. The order matters whenever the decorators change the result.

8. More useful decorators

A registry

A decorator does not have to wrap anything: it can register the function and return it unchanged:

registry = {}

def register(name):
    def deco(func):
        registry[name] = func
        return func
    return deco

@register("double")
def double(x):
    return x * 2

@register("neg")
def neg(x):
    return -x

print(sorted(registry))
print(registry["double"](4), double(5))
['double', 'neg']
8 10

This is how many frameworks collect handlers and commands: a decorator marks the function, and the program finds them in registry.

Retry

A wrapper can run the function again when it fails (exceptions are chapter 14):

def retry(times):
    def deco(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            last = None
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except ValueError as e:
                    last = e
                    print(f"attempt {attempt} failed: {e}")
            raise last
        return wrapper
    return deco

state = {"n": 0}

@retry(3)
def flaky():
    state["n"] += 1
    if state["n"] < 3:
        raise ValueError("not yet")
    return "ok"

print(flaky())
attempt 1 failed: not yet
attempt 2 failed: not yet
ok

The function failed twice and succeeded on the third try. If all tries fail, the last error is raised again.

Checking arguments

def validate_positive(func):
    @functools.wraps(func)
    def wrapper(n):
        if n < 0:
            raise ValueError("n must be non-negative")
        return func(n)
    return wrapper

@validate_positive
def root(n):
    return n ** 0.5

print(root(16))
root(-1)
4.0
ValueError: n must be non-negative

9. Caching: lru_cache and cache

Remembering results is so useful that Python has it ready-made. functools.lru_cache (lesson 11.6) and functools.cache are decorators:

@functools.lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(30))
info = fib.cache_info()
print(info.misses, info.hits)
832040
31 28

cache_info() shows that the function really ran only 31 times (once for each value from 0 to 30), and the other 28 answers came from the cache. lru_cache(maxsize=N) keeps only the N most recently used results ("least recently used" are dropped). functools.cache (Python 3.9 and later) is the simple, unlimited version.

The arguments must be hashable (lesson 9.7), because they are used as dictionary keys.

10. Class-based decorators

Any callable can be a decorator, including a class whose objects have __call__ (chapter 13):

class Count:
    def __init__(self, func):
        self.func = func
        self.n = 0
        functools.update_wrapper(self, func)

    def __call__(self, *args, **kwargs):
        self.n += 1
        return self.func(*args, **kwargs)

@Count
def hey():
    return "hey"

hey()
hey()
print(hey.n, hey.__name__)
2 hey

This keeps the state as an attribute instead of in a closure. It is the same idea in a different shape.

11. Built-in decorators you will meet

Decorator Use Lesson
@property a method that reads like an attribute chapter 13
@staticmethod, @classmethod methods that do not use the instance chapter 13
@functools.wraps keep a wrapper's name and docstring this lesson
@functools.lru_cache, @functools.cache remember results this lesson
@dataclasses.dataclass generate a class's boilerplate lesson 13.11
@abc.abstractmethod mark a method that subclasses must write lesson 13.10

Worked example: a reusable "log and time" decorator

Combine logging and timing in one decorator, and apply it to two different functions.

import functools
import time

def traced(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - start
        shown = [repr(a) for a in args] + [f"{k}={v!r}" for k, v in kwargs.items()]
        print(f"{func.__name__}({', '.join(shown)}) -> {result!r}")
        wrapper.last = elapsed
        return result
    return wrapper

@traced
def mean(values):
    """Return the average of a list."""
    return sum(values) / len(values)

@traced
def clamp(value, low=0, high=10):
    return max(low, min(value, high))

mean([4, 8, 6])
clamp(15)
clamp(-3, low=-1)
print(mean.__name__, mean.__doc__)
print(mean.last >= 0)
mean([4, 8, 6]) -> 6.0
clamp(15) -> 10
clamp(-3, low=-1) -> -1
mean Return the average of a list.
True
Part Why
*args, **kwargs one decorator fits functions with any parameters
functools.wraps mean keeps its name and docstring
return result the caller still gets the real answer
wrapper.last the last run time is kept as an attribute

The decorated functions are used exactly as before, and the logging code is written once. The values are made up.

Common mistakes

  • Forgetting to return the result from the wrapper.
  • Forgetting *args, **kwargs, so the decorator breaks for other signatures.
  • Forgetting functools.wraps, so names and docstrings are lost.
  • Writing @repeat instead of @repeat(3) for a decorator that needs an argument (the function is passed in as times).
  • Calling the function inside the decorator instead of returning the wrapper.
  • Stacking decorators and not realising the bottom one applies first.

Key takeaways

  • A decorator takes a function and returns a new function; @name above a def means f = name(f).
  • The wrapper takes *args, **kwargs, calls the original, and returns its result.
  • Use @functools.wraps(func) on the wrapper to keep the original name and docstring.
  • A decorator with arguments needs one more layer: repeat(3) returns the real decorator.
  • Stacked decorators apply from the bottom up; lru_cache and cache are ready-made caching decorators.

Practice

1. What does @shout above def greet(...) do?

Show answer

It replaces greet with shout(greet): the same as writing greet = shout(greet) after the function.

2. Why must the wrapper return the result of the function?

Show answer

Otherwise the decorated function returns None instead of the real answer.

3. What problem does functools.wraps solve?

Show answer

Without it, the decorated function shows the wrapper's name and docstring (wrapper, None). With it, the original name, docstring and other details are kept.

4. In what order are @a and @b applied in @a above @b above def f?

Show answer

@b first (the closest to the function), then @a: f = a(b(f)).

5. Why does a decorator with an argument, such as @repeat(3), need three nested functions?

Show answer

The outer function takes the setting (3) and returns the real decorator. The middle function takes the function being decorated. The inner function is the wrapper that takes each call's arguments.

6. Make slow_square(n) fast for repeated calls with one line.

Show answer

Put @functools.lru_cache(maxsize=None) (or @functools.cache) above its def.