What Is a Decorator in Python? Explained With Examples

A Python decorator wraps a function to add behavior before or after it runs, without changing the function's own code. Learn the @ syntax and how it works.

Published September 17, 2026

A decorator is a function that wraps another function to add behaviour without changing its code. You apply it with the @name syntax above the function definition.

The concept

Functions are objects in Python, so you can pass them to other functions and return new ones. A decorator takes a function, returns a wrapper around it, and the name now points at the wrapper.

@decorator above def f is shorthand for f = decorator(f). Use functools.wraps so the wrapper keeps the original name and docstring.

A call through the decorator

calldelegatesCallerf()Wrapperbefore / afterOriginal freal work
The wrapper runs code before and after the real function.

Practical examples

Timing decorator

import time, functools

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

@timed
def work():
    sum(range(10**6))

Decorator with arguments

def repeat(n):
    def deco(fn):
        def wrapper(*a, **k):
            for _ in range(n):
                fn(*a, **k)
        return wrapper
    return deco

@repeat(3)
def hi(): print('hi')

Built-in decorators

class A:
    @staticmethod
    def util(): ...
    @property
    def size(self): return 1

Common mistakes

  • Forgetting functools.wraps, so help() and debuggers show 'wrapper'.
  • Not returning the wrapped function's result.
  • Forgetting *args, **kwargs so the wrapper breaks for functions with parameters.

Key takeaways

  • @d on f means f = d(f).
  • Wrappers take *args, **kwargs and return the result.
  • Use functools.wraps.

FAQ

Can I stack decorators?

Yes; they apply from the bottom up, the closest one wraps first.

Where are decorators used?

Logging, caching (functools.lru_cache), authentication checks and web routes (Flask @app.route).

More Python articles