Python Programming

Python Decorators

A decorator can change what a Python function does without rewriting the function itself. Written with the compact @ syntax, it places a layer of behavior around a callable—useful for logging, timing, access checks, and other recurring tasks. The idea is easier to understand when you follow the journey from a function, to a wrapper, to the decorator that connects them.

Decorators.cc is primarily a practical guide to the choices that shape homes and rooms. Here, the same word belongs to another craft: programming. In both settings, the useful question is what a layer adds—and whether it helps the underlying structure work better.

What is a decorator?

In Python, a decorator is a callable that takes another callable and returns a callable. Most often, the original callable is a function. The returned function may run extra code before or after the original, change how it is called, or decide whether to call it at all.

Think of a function as a well-defined task. A decorator adds a reusable layer around that task without requiring every call site to repeat the same supporting steps. One wrapper might record when a function runs; another could check permissions or cache a result.

The word “decorator” also has a familiar meaning outside programming: a person or technique that adds a considered layer to a room. The analogy is not exact, but it offers a useful starting point. In either case, the added layer should serve a purpose and work with what is already there.

The foundation: functions are objects

Python functions can be assigned to variables, passed to other functions, and returned as results. That flexibility makes decorators possible. A decorator receives a function just as an ordinary function might receive a number or a string.

def greet(name):
    return f"Hello, {name}!"

same_greet = greet
print(same_greet("Mina"))

Here, same_greet refers to the same function as greet. No copy has been made. Once that idea is clear, the next step—passing a function into a wrapper—becomes much less mysterious.

Build a wrapper by hand

A wrapper is a function that calls another function while adding behavior around it. This example announces each call, then returns the original function’s result.

def announce(func):
    def wrapper():
        print("Starting the function")
        result = func()
        print("The function has finished")
        return result
    return wrapper

def say_hello():
    return "Hello!"

say_hello = announce(say_hello)
print(say_hello())

Calling announce(say_hello) creates a new function, wrapper, which remembers the original say_hello. When the new function runs, it prints a message, calls the original, and passes its result back.

Notice the return result. A wrapper should generally preserve the decorated function’s return value. Omitting that line can silently turn a useful result into None.

What the @ syntax means

Python’s decorator syntax is shorthand for the reassignment shown above. Put a decorator directly above a function definition, and Python passes the newly defined function to that decorator, then binds the name to the returned callable.

def announce(func):
    def wrapper():
        print("Starting the function")
        result = func()
        print("The function has finished")
        return result
    return wrapper

@announce
def say_hello():
    return "Hello!"

This is equivalent in effect to writing say_hello = announce(say_hello) after the function definition. The @ is not a special kind of function; it is a readable way to express the transformation.

Accepting arguments and returning values

The first wrapper accepts no arguments, so it only works for functions that also take none. A more reusable wrapper uses *args and **kwargs to forward positional and keyword arguments, then returns the result.

from functools import wraps

def announce(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} finished")
        return result
    return wrapper

@announce
def multiply(a, b):
    return a * b

print(multiply(3, 4))

This wrapper can handle different function signatures. It also preserves the function’s return value, so callers can use the decorated function much as they would use the original.

Why functools.wraps matters

Without extra care, a decorated function can appear to be named wrapper, because that is the function callers now reach. Its documentation string and other identifying metadata may also be obscured. This can make debugging, help output, and inspection less clear.

The standard-library helper functools.wraps copies important metadata from the original function onto the wrapper. It is applied to the wrapper function inside the decorator:

from functools import wraps

def announce(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

Using @wraps(func) is a small habit with a large effect on clarity. It helps the decorated function retain the identity readers and tools expect, even though a wrapper now sits between the caller and the original implementation.

Decorators with their own arguments

Sometimes you want to configure the decorator—for example, to choose how many times a function should be retried. In that case, add an outer function to receive the decorator’s settings. That outer function returns the actual decorator, which then receives the function.

from functools import wraps

def repeat(times):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            result = None
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def greet(name):
    print(f"Hello, {name}!")

The expression @repeat(3) first calls repeat(3). That produces a decorator configured with the value 3. Python then applies that decorator to greet.

In practical code, make the intended behavior explicit. This example runs the function three times and returns only the final result; it is not a retry mechanism and does not handle exceptions. A real retry decorator would need clearly specified rules for which failures to catch, how long to wait, and when to stop.

Useful patterns: logging and timing

Logging calls

A logging decorator can record that a function was called, and—when appropriate—capture selected arguments or outcomes. This can help reveal the path a program takes without scattering repeated print statements throughout the core logic.

In production applications, Python’s logging module is generally more flexible than printing directly: it supports levels, formatting, and configurable destinations.

Measuring elapsed time

A timing decorator can record a start time, call the function, then calculate how long the call took. This is useful for observation, but a single measurement is not a reliable performance benchmark: machine load, input size, and other conditions can affect the result.

Measure with a suitable tool and representative workloads before optimizing. Timing a function is a clue, not a verdict.

Execution order and stacked decorators

Decorators are applied when Python executes a function definition—not each time the function is called. The decorated name is rebound to the callable returned by the decorator. This distinction matters when reading code: the definition establishes the wrapper; later calls run through it.

Multiple decorators can be stacked:

@first
@second
def work():
    pass

The effect is equivalent to work = first(second(work)). The decorator nearest the function is applied first, then the one above it. Their order can change behavior, so when a stack seems confusing, expand it into the equivalent nested expression.

This is one reason decorators work best when each layer has a clear, limited responsibility. A short stack of understandable transformations is easier to reason about than a dense chain whose order is unclear.

Closures and common pitfalls

A wrapper often refers to func, a variable from the surrounding decorator function. The wrapper can still access that variable after the outer function has returned; this retained reference is part of a closure. It is what allows the wrapper to call the original function later.

  • Forgetting to return the wrapper: The decorated name may become None if the decorator does not return a callable.
  • Dropping arguments: A wrapper with a fixed signature may reject calls the original function accepts. Use *args and **kwargs when the decorator is intended to be general.
  • Dropping the return value: If the wrapper calls the original but does not return its result, callers lose that result.
  • Skipping wraps: Introspection and documentation may identify the wrapper rather than the original function.
  • Adding surprising side effects: A decorator that changes inputs, suppresses exceptions, or runs a function repeatedly should make that behavior unmistakable.

A decorator is not automatically an improvement. If it hides important control flow or makes a one-off operation harder to find, a normal helper function may be clearer.

Decorating classes

Decorators can be applied to classes as well as functions. A class decorator receives the class object and returns a class—often the original class with added or adjusted behavior. Python’s built-in @dataclass is a familiar example: it inspects a class definition and supplies commonly needed methods, such as an initializer, according to the class’s fields.

The same basic rule holds: a decorator transforms the object named in the definition and returns the object that will be bound to that name. For classes, consider carefully whether the transformation preserves the behavior and identity that users of the class rely on.

When should you use a decorator?

Decorators are particularly useful when the same supporting behavior belongs around several functions: authorization checks, logging, caching, validation, or instrumentation. They can keep that behavior consistent while allowing each function to focus on its main task.

Choose a straightforward helper instead when the behavior is used once, depends on many hidden conditions, or would be easier to understand at the point of use. Good abstraction is not about using the most compact syntax; it is about making the program’s intentions easier to follow.

Decorators also have counterparts in other languages, though the details differ. For a comparison of class and class-element transformations in another ecosystem, see JavaScript Decorators.

A practical checklist

  • Remember that @decorator is shorthand for applying a callable to a function and rebinding its name.
  • Use a wrapper to add behavior before or after the original call.
  • Forward arguments with *args and **kwargs when needed, and return the original result.
  • Use functools.wraps to preserve useful function metadata.
  • For configurable decorators, separate the settings function, decorator, and wrapper into clear layers.
  • Check stacked decorator order and keep side effects easy to recognize.

A small layer, carefully chosen

The first decorator can seem like a trick hidden behind a symbol. It is not: it is a function receiving another function, returning a callable, and giving that callable the original name. Once the steps are visible, the @ syntax becomes a concise way to express a deliberate design choice—one layer of behavior, added where it belongs.

Theme