🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Python Decorators — Function Enhancement Patterns

Python AdvancedDecorators🟢 Free Lesson

Python Decorators — Function Enhancement Patterns

A decorator is a callable that takes a function and returns another callable, usually wrapping the original so extra behavior runs before, after, or instead of it. The syntax is common in frameworks: route registration, permission checks, caching, transaction boundaries, and test fixtures are all decorators in popular libraries. What is less commonly taught is that the mechanism has no special status in the interpreter. The decorator syntax is a rebind, and understanding that single fact removes most of the confusion about arguments, stacking, and classes.

What You'll Learn

  • 1Explain decorator syntax as a name rebinding operation
  • 2Preserve function metadata so frameworks and debuggers keep working
  • 3Write decorator factories that work with and without arguments
  • 4Apply decorators to functions, methods, and classes with predictable stacking order

The syntax is a rebind, not a keyword

Python has no decorator keyword. When the interpreter executes a decorated definition, it first creates the undecorated function object, then looks up the name that appears after the at sign, calls it with the function as the single argument, and binds the result back to the original name. That is the whole feature. Everything else falls out of the fact that functions are ordinary objects and names are just labels.

python
import time
from functools import wraps


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


def plain():
    time.sleep(0.05)
    return "ok"


print(plain.__name__)      # plain
plain = slow(plain)        # what @slow does
print(plain.__name__)      # still plain, because of wraps
print(plain())

Because the operation is a rebind, the decorated name no longer refers to the original function object. Anything that stored a reference to the original before decoration still has it; anything that looks up the name afterwards sees the wrapper. That is also why a decorator defined in one module and applied in another affects only the applying module's binding.

Metadata is part of the contract

A wrapper without functools.wraps reports its own name, its own empty docstring, and no reference to the function it replaced. That breaks real systems rather than merely looking untidy. Documentation generators lose the docstring. Profilers and tracebacks name the wrapper, so the stack shows fifty identical frames. Frameworks that inspect signatures to build dependency injection, such as FastAPI, click, and pytest, read the wrapper's signature and fail to find parameters they need.

functools.wraps copies __module__, __name__, __qualname__, __doc__, __dict__, and, importantly, sets __wrapped__ to the original function, which inspect.signature follows automatically. The habit is not optional polish; it is the difference between a decorator that composes with the ecosystem and one that quietly degrades it.

python
import inspect
from functools import wraps


def logged(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        print(f"calling {fn.__name__} with {args} {kwargs}")
        return fn(*args, **kwargs)
    return wrapper


@logged
def transfer(account: str, amount: float, *, currency: str = "EUR") -> float:
    """Move money between accounts."""
    return amount


print(inspect.signature(transfer))
print(transfer.__doc__)
transfer("alice", 10.0, currency="USD")

Factories, and the pattern that works both ways

When a decorator itself takes arguments, an extra layer of function appears: the factory receives the arguments and returns the decorator that receives the function. This trips people up because @retry and @retry(3) call the same name with different arguments. The dual-mode pattern accepts a callable in the first position and treats it as the decorated function when present, which lets one implementation serve both call styles.

python
import random
from functools import partial


def retry(func=None, *, attempts=3, delay=0.5, exceptions=(Exception,)):
    def decorate(target):
        @wraps(target)
        def wrapper(*args, **kwargs):
            for attempt in range(1, attempts + 1):
                try:
                    return target(*args, **kwargs)
                except exceptions:
                    if attempt == attempts:
                        raise
                    time.sleep(delay)
        return wrapper

    if callable(func):
        return decorate(func)
    return decorate


@retry
def ping_a():
    pass


@retry(attempts=5, delay=0.1)
def ping_b():
    pass

The same shape can be written with functools.partial instead of an explicit if, which some teams find clearer. Either way, keep the keyword-only markers on the configuration arguments; without the star, positional callers can accidentally bind a function into the attempts slot.

Stacking, ordering, and where arguments flow

Decorators stacked on one definition apply bottom up and run top down. @a @b def f is exactly f = a(b(f)), so the outermost decorator is the first to see a call and the last to see the return value. Getting this wrong produces bugs that look like caching failures but are really ordering mistakes, such as a rate limiter inside a retry loop multiplying the effective request count.

StackingEquivalent toRuns on callNotes
@af = a(f)a then fThe simple case
@a @bf = a(b(f))a, b, then fb's result is what a wraps
@a(1) @bf = a(1)(b(f))a, b, then fFactory evaluated at definition time
@a @b(2)f = a(b(2)(f))a, b, then fInner factory runs first

Argument flow matters for stateful decorators. A factory's configuration is captured once when the module is imported, while per-call state belongs in the wrapper's closure or on the function object itself. Confusing the two is how a rate limiter ends up sharing one timestamp across every instance of the decorated function.

Five shapes worth memorising

Almost every production decorator falls into one of five shapes, and recognising the shape tells you where the state goes. A timing decorator measures before and after and logs the difference, with no arguments of its own. A retry decorator loops around the call and sleeps between attempts, which makes it a factory because the attempt count is configuration. A caching decorator stores results keyed by arguments, which means it must think about unhashable inputs and about staleness. A validation decorator inspects arguments against a specification before calling, and must decide whether to check keyword-only parameters too. A registration decorator does not wrap at all: it records the function in a registry and returns it unchanged, which surprises people the first time they meet it because the wrapper is missing entirely.

Knowing that registration decorators return the original object is a small thing that prevents a large class of confusion, including bugs where a registered handler loses its signature and breaks a framework that inspects it. When you write a decorator and find yourself looping, sleeping, storing, or inspecting, name the shape out loud; it will usually tell you the missing piece, such as a cap on the sleep duration or a lock around the store.

Decorating methods and classes

Methods are functions that happen to live on a class, so the same decorators apply, with one wrinkle: the first argument is the instance. A decorator that inspects positional arguments must account for it. Static and class methods compose predictably when applied in the right order, and property is itself a descriptor rather than a decorator factory, which is why @x.setter needs the getter to exist first.

Class decorators receive the class and usually return either the class after mutation or a replacement object. A singleton class decorator that returns a factory function is a common example, and a common mistake: after decoration the name no longer refers to a class, so isinstance checks and subclassing break unless you return the class itself or a subclass.

Debugging a decorated stack

When something goes wrong under a pile of decorators, peel them off one at a time and verify the name and signature after each removal. inspect.signature shows what frameworks will see. print(wrapper.__wrapped__) walks back to the original. Disabling a decorator temporarily should be a one-line change; if it is not, the decorator is doing more than it should.

Keep decorators small and single-purpose. A decorator that logs, retries, caches, and validates is four review problems in one indirection, and the failure mode will always be attributed to the wrong concern. Compose four small decorators instead, and pin their order with a test.

Common Mistakes

Omitting functools.wraps so names, docs, and signatures vanish

Fix: Apply wraps on every wrapper, and add a test that checks inspect.signature of a decorated function

Hard-coding positional parameters in a wrapper

Fix: Use *args and **kwargs so the decorator works with any call pattern, including keyword-only arguments

Confusing factory arguments with per-call state

Fix: Capture configuration in the factory closure and keep mutable per-call state inside the wrapper

Returning a function from a decorator applied to a class when subclassing is needed

Fix: Return the mutated class or a subclass so isinstance and inheritance keep working

Best Practices

  • Treat functools.wraps as mandatory on every wrapper
  • Make configuration arguments keyword-only to avoid binding mistakes
  • Keep one concern per decorator and compose them in a deliberate order
  • Expose __wrapped__ and use it when debugging to reach the original implementation
  • Write a small test that pins the stacking order of decorators you rely on

Interview Questions

Q1: What does @timer actually execute at definition time?

It calls timer with the freshly defined function and rebinds the name to whatever timer returns, typically a closure named wrapper. No call to the decorated function happens at decoration time.

Q2: Why does a decorator factory need an extra nested function?

The factory receives the configuration and must return the object that receives the function. One extra level turns arguments given at definition time into a callable that can accept the function.

Q3: How do you debug a stack of decorators quickly?

Remove them one at a time, checking inspect.signature and __wrapped__ after each step to see which layer changed the name, signature, or behavior you are investigating.

Key Takeaways

  • Decoration is a name rebind: call the decorator with the function, bind the result
  • functools.wraps preserves the metadata that frameworks, profilers, and debuggers depend on
  • Factories add one nesting level so configuration and the function stay separate arguments
  • Stacked decorators apply bottom up and run top down; pin the order with a test
  • Keep each decorator single-purpose and compose them rather than building one that does everything
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement