agyanadda@gmail.com

Python Decorators

Advanced Python 1 min read Updated Dec 4, 2026 Topic 26 of 32

A decorator wraps a function to add behaviour without changing its code — logging, timing, caching, access checks.

Functions are objects

In Python you can pass functions as arguments and return them from other functions. Decorators build on this.

How it works

@timer
def report(): ...

is the same as report = timer(report).

The decorator returns a wrapper function that runs extra code before and/or after calling the original.

Use functools.wraps

@functools.wraps(func) on the wrapper keeps the original function's name and docstring.

Accept any arguments

Write the wrapper as def wrapper(*args, **kwargs): so it works with any function.

Decorators with arguments

@retry(times=3) needs one more level: a function that returns a decorator.

Built-in and common decorators

  • @property, @classmethod, @staticmethod
  • @functools.cache / @lru_cache — remember results
  • @dataclass
  • Framework routes: @app.route("/") in Flask, @app.get("/") in FastAPI

Example

Example — Timer and retry decorators Python
import functools, time, random

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
        return result
    return wrapper

def retry(times=3):
    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 e:
                    print(f"Attempt {attempt} failed: {e}")
            raise ConnectionError("All attempts failed")
        return wrapper
    return decorator

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

@retry(times=3)
def flaky_api():
    if random.random() < 0.6:
        raise ConnectionError("timeout")
    return "data received"

print(slow_sum(5_000_000))
print(flaky_api())

@functools.cache
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80))

Prints the sum and how long it took (e.g. "slow_sum took 0.080s"), up to two failed attempts before "data received" (random, and it may fail all three times), and fib(80) = 23416728348467685 instantly thanks to caching.

Test Yourself With Exercises

Exercise 1 Multiple Choice

@timer above def f() is the same as…

Exercise 2 True / False

functools.wraps keeps the original function's name and docstring.

Exercise 3 Fill in the Blank

Cache function results with @functools.___

Frequently Asked Questions

Web frameworks use them for routes and login checks (@app.route, @login_required), testing libraries use them for fixtures, and they are common for logging, caching, retries, rate limiting and timing.