Python · Module 4 · Lesson 41 min read

Decorators

What is a decorator?

A function that wraps another function to add behaviour (logging, timing, caching, permission checks) without changing its code.

@timer above a function is shorthand for slow_add = timer(slow_add).

The pattern

Python
import functools

def my_decorator(func):
    @functools.wraps(func)          # keeps the original name & docstring
    def wrapper(*args, **kwargs):
        # before
        result = func(*args, **kwargs)
        # after
        return result
    return wrapper
  • *args, **kwargs let the wrapper accept any arguments.
  • Always return the result, or the decorated function returns None.
  • @functools.wraps keeps func.__name__ correct for debugging.

Built-in decorators you'll meet

@property, @staticmethod, @classmethod, @functools.lru_cache (memoisation), @dataclass.

▶️ Runs in the app.

Example

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

@timer
def sum_to(n):
    return sum(range(n))

print(sum_to(1_000_000))      # sum_to took 0.0xxx s / 499999500000

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

print(fib(80))                # 23416728348467685 — instant thanks to caching