Open almost any Python web project and you will see lines starting with an @ sign sitting above function definitions: a route in Flask, login_required in Django, pytest.fixture, functools.lru_cache, dataclass. They look like annotations, a bit of metadata attached to a function. They are not. Each one is an ordinary function call that runs when Python reaches the definition, and whatever it returns replaces your function. Once that clicks, decorators stop being magic and become a tool you can write yourself.
The two facts underneath
Decorators rest on two features of Python.
First, functions are objects. You can assign a function to a variable, put it in a dictionary, pass it to another function and return it from one. Nothing special is needed.
Second, a function defined inside another function can use the outer function’s variables, even after the outer function has returned. The inner function “closes over” those variables, which is why it is called a closure.
Put them together and you get the decorator pattern. A decorator is a function that accepts a function, defines an inner wrapper that calls the original with some extra behaviour before or after, and returns the wrapper. Writing the @ line above a definition is shorthand: Python defines your function, passes it to the decorator, and binds the name to whatever comes back. Decorating a function called generate_invoice with a decorator called timed is exactly equivalent to defining it normally and then writing that generate_invoice equals timed applied to generate_invoice.
Walking through a timing decorator
Suppose a billing team wants to log how long certain functions take. The decorator, in prose, does this:
- It receives the original function as its argument.
- It defines a wrapper that accepts any positional and keyword arguments, using
*argsand**kwargs, so it can stand in for a function of any signature. - Inside the wrapper, it records the start time with
time.perf_counter, which is designed for measuring intervals, calls the original function with the same arguments, records the end time, and logs the function’s name with the elapsed milliseconds. - The wrapper returns whatever the original returned, so callers see no difference except the log line.
- The decorator returns the wrapper.
Two details are easy to get wrong. If the wrapper forgets to return the original result, every decorated function silently starts returning None. And if the original function raises an exception, a naive wrapper skips its logging. Putting the timing in a try and finally structure ensures the duration is logged whether the call succeeded or failed.
Keep the original’s identity with functools.wraps
After decoration, the name generate_invoice points to the wrapper. Its __name__ attribute now says “wrapper”, its docstring is gone, and tools that inspect it, such as documentation generators, debuggers, logging that prints function names and frameworks that register functions by name, see the wrong thing. Flask, for example, uses a view function’s name as its default endpoint name, so two routes decorated with the same naive decorator can clash because both look like “wrapper”.
The standard fix is to decorate the wrapper itself with functools.wraps, passing it the original function. It copies the name, docstring, module and other metadata onto the wrapper and stores a reference to the original in a __wrapped__ attribute. Treat it as mandatory in any decorator you write.
Decorators that take arguments
Sometimes you want configuration: log only if the call takes longer than 200 milliseconds, or retry up to 3 times. A decorator with arguments adds one more layer. The outermost function takes the configuration and returns the actual decorator, which takes the function and returns the wrapper. So writing @slow_log(threshold_ms=200) first calls slow_log with 200, gets back a decorator, and then applies that to your function.
This three-level nesting is where most confusion comes from. A useful check: whatever expression follows the @ sign must evaluate to something that accepts a function. @slow_log without parentheses passes your function in as the threshold, which is a common bug.
Stacking order and timing
When several decorators are stacked, the one nearest the function is applied first, and the one at the top wraps everything beneath it. At call time, the outermost wrapper runs first. With an authentication decorator and a caching decorator, the order matters a great deal: if caching is outside authentication, a cached response could be returned without checking who is asking. Read stacks from the top down as “this happens first when the function is called”.
Decorators also run at import time, once, when the module is loaded. That is how a Flask route decorator registers your function in the application’s URL map before any request arrives. It also means a decorator that does expensive work or depends on configuration not yet loaded will cause trouble at import. Keep the decoration step light and put real work inside the wrapper.
Good uses and poor ones
Decorators are best for cross-cutting behaviour that is unrelated to what the function does: timing, logging, retries, caching, permission checks, input validation, transaction boundaries and registration in a framework. The standard library offers several ready-made ones worth knowing, including lru_cache and cache for memoisation, contextmanager for turning a generator into a context manager, and property, staticmethod and classmethod for classes.
They are a poor fit when they hide important control flow. A decorator that quietly swallows exceptions, rewrites arguments or changes the return type makes the function lie about what it does, and someone reading the body alone will be misled. Retries deserve particular care: a retry decorator on a function that charges a card or sends an SMS can repeat side effects unless the operation is idempotent. When a decorator changes behaviour that a caller depends on, a plain explicit call in the function body is usually clearer.
Class decorators follow the same mechanics with a class instead of a function. dataclass is the familiar example: it takes your class, generates methods such as the initialiser and equality comparison from its annotated fields, and returns the enhanced class.
Written by the RP Strativa Team. Thresholds in the examples are illustrative.
Leave a Reply