Learning Tips | Published Nov 16, 2026 | 7 min read

Python Decorators and Wrappers

Learn how Python decorators wrap functions, preserve metadata with functools.wraps, accept options, and compose in order.

Diagram showing a decorator transforming an original function into a wrapper that adds behavior and returns the original result

A Python decorator wraps or replaces a function with another callable, often to add behavior such as timing, logging, or access checks. This guide explains how @ syntax works, how to preserve function metadata with functools.wraps, how decorator factories capture options, and when a decorator is the right abstraction.

What the @ syntax does

A decorator is a callable applied to a function when the function is defined. The common syntax @decorate above a function is roughly equivalent to defining the function and then assigning function = decorate(function). The decorator's returned object is bound to the function's name.

This means decorators are not automatically run every time the decorated function is called. The decorator expression is evaluated at definition time; a wrapper function returned by the decorator may then run on each later call.

Build a simple timing decorator

A decorator often defines an inner wrapper that receives the original function's arguments, performs extra work, and returns the original result:

from functools import wraps
from time import perf_counter

def timed(function):
    @wraps(function)
    def wrapper(*args, **kwargs):
        started = perf_counter()
        try:
            return function(*args, **kwargs)
        finally:
            elapsed = perf_counter() - started
            print(f"{function.__name__}: {elapsed:.4f}s")
    return wrapper

@timed
def total_price(prices):
    return sum(prices)

print(total_price([10, 20, 30]))

The wrapper uses *args and **kwargs so it can forward positional and keyword arguments. Its try/finally records elapsed time even if the wrapped function raises an exception, while allowing that exception to propagate. In reusable code, prefer a logger or injected reporting function over printing directly.

Preserve metadata with functools.wraps

Without @wraps(function), tools that inspect the decorated callable may see the inner function's name and docstring instead of the original's. functools.wraps copies useful metadata and sets __wrapped__, which helps documentation tools, debuggers, and introspection. Include it on wrappers unless you have a deliberate reason not to.

A wrapper should also preserve the wrapped function's return value and exception behavior unless changing them is the explicit purpose of the decorator. A decorator that swallows errors or forgets to return a result can silently change a function's contract.

Use a decorator factory for options

When a decorator needs configuration, add an outer function that accepts the options and returns the actual decorator:

from functools import wraps

def require_role(role):
    def decorate(function):
        @wraps(function)
        def wrapper(user, *args, **kwargs):
            if role not in user.roles:
                raise PermissionError(f"Requires role: {role}")
            return function(user, *args, **kwargs)
        return wrapper
    return decorate

@require_role("editor")
def publish_article(user, article_id):
    return f"Published {article_id}"

Here require_role("editor") creates a decorator configured with the required role; that decorator then wraps publish_article. In a real application, authentication and authorization should use the framework's supported security mechanisms. A small example is not a substitute for a complete security design.

For a configured decorator, keep the configuration and the wrapper's job separate: the outer factory captures options once, the decorator receives the function, and the inner wrapper handles each call. This separation makes it easier to unit-test the policy independently and to see which values are fixed when the function is defined.

For example, a retry decorator would need an explicit policy for which exceptions are retryable, how many attempts are allowed, and whether delay is appropriate. Retrying every exception can hide programming errors or repeat a non-idempotent side effect. Prefer a library or framework mechanism when it already provides the required behavior.

Stacking decorators

Multiple decorators are applied from the closest one to the function outward. For example:

@first
@second
def work():
    pass

is equivalent in effect to work = first(second(work)). Order matters because each decorator receives the result returned by the one below it. When wrappers change arguments, exceptions, or return values, document the order and test the combined behavior.

Common mistakes and practical limits

  • Forgetting wraps: metadata and introspection become misleading.
  • Dropping the return value: return the wrapped call's result unless intentionally changing the API.
  • Changing exception behavior unexpectedly: cleanup can use finally without hiding exceptions.
  • Capturing mutable options: be careful with shared mutable state in decorator factories, especially when wrappers are called concurrently.
  • Overusing decorators: a helper function or explicit call may be easier to understand when behavior is local or highly stateful.
  • Assuming sync wrappers handle async functions: an ordinary wrapper does not automatically await an asynchronous function; write an async def wrapper when the decorated callable is async.

Decorators fit cross-cutting behavior applied consistently around functions. Keep them small, preserve the callable's contract, and make important effects visible to readers.

Further reading

Want a structured Java learning path?

Explore Jaipur Engineers course options to connect Java fundamentals, debugging, backend development and project practice in a guided learning plan.

Explore the Java program   Ask for course guidance