Skip to content

Module 17 · Advanced Python Concepts — topic 9 of 14

Decorators

Wrapping functions to add behaviour: the @ syntax, writing decorators with *args and **kwargs, preserving metadata with functools.wraps, decorators that take arguments, and stacking decorators.

Beginner 12 min read·Lesson 255 of 306 in Python Programming

Learning objectives

  • Write decorators with functools.wraps
  • Create decorators that take arguments
  • Recognise common uses such as logging, retrying and validation

Definition

A decorator is a callable that takes a function and returns a replacement, usually a wrapper that adds behaviour before or after calling the original. @decorator above a def is shorthand for func = decorator(func).

Introduction

Logging every call, timing functions, checking permissions, retrying network calls — decorators add such behaviour without touching the function's own code.

Why it matters

Decorators keep cross-cutting concerns in one place and appear throughout frameworks (@app.route, @property, @pytest.fixture).

Detailed explanation

@my_decorator on a function means func = my_decorator(func), applied once when the function is defined.

A typical decorator defines an inner wrapper(*args, **kwargs) that does extra work, calls func(*args, **kwargs), and returns its result.

Without functools.wraps, the wrapper hides the original's __name__ and __doc__; @functools.wraps(func) copies them over.

A decorator with arguments is a function that returns a decorator: @retry(times=3) calls retry(3), and the result decorates the function.

Stacked decorators apply from the bottom up: @a above @b means func = a(b(func)).

Decorators can store state on the wrapper (such as call counts) or validate arguments before calling the original.

Built-in decorators include @property, @staticmethod, @classmethod, @functools.lru_cache and @dataclasses.dataclass.

Because decoration happens when the def statement runs, any code in the decorator outside the wrapper runs once at import time, while code inside the wrapper runs on every call. Keeping that distinction in mind explains most decorator surprises.

Syntax

Python
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("calling", func.__name__)
return func(*args, **kwargs)
return wrapper
@log_calls
def add(a, b):
return a + b
  • @d means func = d(func).
  • Always use functools.wraps.
  • Factories create decorators with arguments.

Code examples

A logging decorator

Python
def announce(func):
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}{args}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@announce
def add(a, b):
return a + b
add(2, 3)
Output
calling add(2, 3)
add returned 5

Why functools.wraps matters

Python
import functools
def plain(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def proper(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@plain
def f():
"""Docs for f."""
@proper
def g():
"""Docs for g."""
print(f.__name__, f.__doc__)
print(g.__name__, g.__doc__)
Output
wrapper None
g Docs for g.

More examples

Retrying and validating

Python
import functools
def retry(times):
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(f"gave up after {times} attempts")
return wrapper
return decorator
responses = iter([ConnectionError("timeout"), ConnectionError("reset"), "data"])
@retry(times=3)
def fetch():
r = next(responses)
if isinstance(r, Exception):
raise r
return r
print(fetch())
def require_positive(func):
@functools.wraps(func)
def wrapper(x):
if x <= 0:
raise ValueError(f"{func.__name__} needs a positive number, got {x}")
return func(x)
return wrapper
@require_positive
def sqrt(x):
return x ** 0.5
print(sqrt(16))
try:
sqrt(-4)
except ValueError as e:
print(e)
Output
attempt 1 failed: timeout
attempt 2 failed: reset
data
4.0
sqrt needs a positive number, got -4

Step-by-step explanation

  • retry(times=3) returns the real decorator, which wraps fetch.
  • The first two simulated calls raise ConnectionError and are retried; the third succeeds.
  • require_positive checks the argument before the original function runs.

Expected output

Running “Retrying and validating” prints exactly:

TextOutput
attempt 1 failed: timeout
attempt 2 failed: reset
data
4.0
sqrt needs a positive number, got -4

Practical applications

  • Flask's @app.route and FastAPI's @app.get.
  • Authentication checks such as @login_required.

Best practices

  • Use functools.wraps in every wrapper.
  • Accept *args and **kwargs.
  • Keep decorators small and focused.

Common mistakes

Forgetting to return the result

Avoid

def wrapper(*args):
func(*args)

Prefer

def wrapper(*args):
return func(*args)

Without return, every decorated function returns None.

Calling the function in the decorator

Avoid

def deco(func):
func()
return func

Prefer

def deco(func):
@functools.wraps(func)
def wrapper(*a, **k):
return func(*a, **k)
return wrapper

Decorators run at definition time; the call should happen inside the wrapper.

Important notes

  • Classes can also be decorated, and classes with __call__ can act as decorators.

Key takeaways

  • Decorators wrap functions to add behaviour.
  • functools.wraps keeps the original's metadata.
  • Decorator factories take arguments.

Try it yourself

  1. 1
    Write a @count_calls decorator that records how many times a function was called.
  2. 2
    Write @timed that prints how long a function took.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

2 questions test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
  • AdvancedWhat is printed?
Practise this topic