A decorator in Python is a callable that takes a function (or class), adds behaviour around it, and returns the replacement. You apply it with the @name syntax on the line above a definition. Decorators are used for logging, timing, caching, access checks, retries and registering handlers without editing the original function body.
@decorator above def f(): ... is exactly the same as writing f = decorator(f) after the definition.
A decorator is a function that accepts a function and returns a function. The usual shape uses an inner wrapper that calls the original.
functools.wraps copies the name, docstring and annotations of the original function onto wrapper. Without it, add.__name__ would be wrapper, which breaks debugging and introspection tools.
When the decorator itself needs configuration, add one more level: a function that returns the decorator.
@retry(times=5, delay=1.0) first calls retry(...), which returns decorator, and then Python applies decorator to fetch.
Decorators apply from the bottom up, so the one closest to the function wraps it first.
This equals work = decorator_a(decorator_b(work)). At call time decorator_a's wrapper runs first, which matters for things like authentication followed by caching.
Any callable object can be a decorator. A class with __call__ is useful when the decorator keeps state.
Decorators can also receive a class, for example @dataclass, which reads the annotations and generates __init__, __repr__ and comparison methods.
| Decorator | Purpose |
|---|---|
@property | Turn a method into a computed attribute |
@staticmethod, @classmethod | Change how a method is bound |
@functools.cache, @functools.lru_cache | Memoize results |
@functools.wraps | Preserve metadata in your own decorators |
@functools.singledispatch | Overload by first-argument type |
@contextlib.contextmanager | Build a context manager from a generator |
@dataclasses.dataclass | Generate boilerplate methods |
Since Python 3.10, ParamSpec lets you type a decorator so the wrapped signature is preserved for type checkers. Python 3.12 adds simpler generic syntax.
functools.wraps?It keeps the original function's __name__, __doc__ and __wrapped__ attribute. Without it, logs, help output and tools such as inspect see the wrapper instead.
They are applied bottom to top, but the outermost wrapper runs first when you call the function.
Yes, but the wrapper must be async def and must await the original call; otherwise you return a coroutine without running your extra logic around it.
A decorator wraps a whole function. A context manager wraps a block using with. contextlib.ContextDecorator lets one object do both.
A Python decorator is a callable that receives a function and returns a replacement, applied with @. Use functools.wraps in every wrapper, add an outer function when the decorator takes arguments, and remember that stacked decorators apply from the bottom up. For typed code, use ParamSpec to keep signatures intact.