Skip to content
IT glossary
ProgrammingUpdated December 3, 2026

Decorator

Декоратор

A decorator adds behavior to an existing object or function without rewriting it. For example, a wrapper can measure how long a function takes while leaving the calculation itself unchanged.

One term, two meanings

Decorator is the name of a structural design pattern. It is also the name of a language feature in Python and some other languages. The pattern describes how to extend an object through a wrapper. Python's @ syntax tells you where a decorator is applied, but it does not tell you what that decorator does: it might wrap a function, register it, or replace it with something else.

How the design pattern works

Suppose a report reads data through a storage interface. To measure read times, you can give the report a timed storage wrapper instead of changing the report or the storage implementation. The wrapper implements the same interface, holds a reference to the underlying storage object, and delegates reads to it while recording their duration. The report still calls the same method.

Because the wrapper and the underlying object share an interface, you can stack wrappers rather than write a subclass for every combination of features. The order determines what each layer sees. Put timing outside a cache and it measures hits as well as misses. Put it inside and it only measures reads that the cache passes through.

A Python example

from functools import wraps

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

@announce
def total(price, quantity):
    return price * quantity

print(total(4, quantity=3))  # Prints 'Calling total', then 12

Think of @announce as total = announce(total) immediately after the function definition. Python applies the decorator when it executes the definition, not each time total is called. On each call, the wrapper uses its closure to reach the original function, forwards the arguments, and returns the original result. functools.wraps preserves metadata such as the function's name and docstring.

Common confusions and interview questions

Logging, metrics, and caching are common uses for wrappers. An adapter also wraps an object, but its job is to expose a different interface. A proxy can keep the same interface too; the distinction is intent. A proxy controls access to an object, while a decorator adds a responsibility that can be combined with others.

In a Python interview, you may be asked to write a decorator that handles positional and keyword arguments without dropping the return value. You may also be asked to trace stacked decorators: with @outer above @inner, the resulting binding is outer(inner(fn)). If both decorators return wrappers that delegate, a call enters the outer wrapper first. Applying the decorators and calling the resulting function are separate events.