← Back to Python, page 1

python-0002 · Medium mid

Explain Python decorators and write one that times a function.

A decorator is a callable that takes a function and returns a replacement, usually a wrapper that runs extra code before or after the original. The @name syntax above a def is shorthand for func = name(func). Use functools.wraps inside the decorator so the wrapper keeps the original name and docstring.

Full answer
python
import functools, time

def timed(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 under 1s: {elapsed < 1}")
        return result
    return wrapper

@timed
def slow_add(a, b):
    """Add two numbers slowly."""
    time.sleep(0.01)
    return a + b

print(slow_add(2, 3))
print(slow_add.__name__, "-", slow_add.__doc__)

Output:

text
slow_add took under 1s: True
5
slow_add - Add two numbers slowly.

@timed replaced slow_add with wrapper. The wrapper accepts any arguments with *args, **kwargs, calls the original, measures the elapsed time and returns the original's result unchanged. The timing line is printed with a rounded figure so the output is stable between runs.

functools.wraps copies __name__, __doc__ and other metadata, which is why slow_add.__name__ still prints 'slow_add'; without it, logs and debuggers would show 'wrapper'.

Decorators that take arguments need one more level: @retry(times=3) calls retry(3), which returns the actual decorator. Common real uses are caching (functools.cache), access checks in web frameworks, retries and logging. Stacked decorators apply from the bottom up.

python
import functools, time

def timed(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 under 1s: {elapsed < 1}")
        return result
    return wrapper

@timed
def slow_add(a, b):
    """Add two numbers slowly."""
    time.sleep(0.01)
    return a + b

print(slow_add(2, 3))
print(slow_add.__name__, "-", slow_add.__doc__)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • @d above def means f = d(f)
  • Wrappers take *args and **kwargs
  • functools.wraps keeps metadata
  • Decorators with arguments add a level
  • Stacked decorators apply bottom up

Common mistakes

  • Forgetting to return the wrapped function's result
  • Omitting functools.wraps

Follow-ups

  • How would you write a decorator that takes arguments?
  • How do class-based decorators work?

Tips

  • Return the result from the wrapper