Python Decorators — @ Syntax, Wrapping, and functools.wraps
A decorator adds behavior around a function without editing its body: logging each call, timing it, checking a permission, or caching its result. The mechanism is small. One function takes another function and returns a replacement, and the @ line above a definition applies that replacement at the moment the function is defined. This guide shows the working core: a first decorator, a wrapper that passes arguments through and returns the result, what the @ line expands to, the order stacked decorators apply in, a decorator that takes its own arguments, keeping the original name and docstring with functools.wraps, and a class-based decorator that holds a call count.
Written November 12, 2026 · Tested with Python 3.12.3 · 8 min read
- The main program: a first decorator
- A wrapper that passes arguments through
- What the @ line expands to
- Stacked decorators apply bottom first
Written November 12, 2026
Tested with Python 3.12.3
What this guide is
A decorator is a function that takes a function as its argument and returns a new function. The returned function usually calls the original somewhere inside itself, with extra work before or after the call. Nothing about the original function's body changes, and the caller cannot tell the difference: it calls the name it always called and gets a result of the same shape. Decorators work because Python functions are ordinary values. A function can be passed as an argument, stored in a variable, and returned from another function, and a decorator uses all three of those facts at once.
The main program: a first decorator
The decorator below prints a line before and after the wrapped function runs. The inner function, named wrapper here, is what actually gets called from then on:
def announce(func):
def wrapper():
print("before")
result = func()
print("after")
return result
return wrapper
@announce
def greet():
print("hello")
return "done"
print(greet())
The exact output:
before
hello
after
done
Calling greet runs wrapper, not the original body directly. The wrapper prints its first line, calls the stored function, prints its second line, and returns what the original returned, so the print at the end shows done. If the wrapper forgot the return, the caller would get None instead of the result. A decorator that swallows the return value is the most common decorator bug, and it fails silently: the wrapped function runs, its prints appear, and only the value is missing.
A wrapper that passes arguments through
Most functions take arguments, so most wrappers must accept whatever the caller passes and hand it on. The args and *kwargs pair in the wrapper signature collects any positional and keyword arguments, and the call inside forwards both:
def logged(func):
def wrapper(*args, **kwargs):
print("call:", func.__name__, args, kwargs)
result = func(*args, **kwargs)
print("result:", result)
return result
return wrapper
@logged
def add(a, b=0):
return a + b
print(add(2, 3))
print(add(10, b=5))
The exact output:
call: add (2, 3) {}
result: 5
5
call: add (10,) {'b': 5}
result: 15
15
The wrapper does not need to know the wrapped function's parameters. It records the call as it arrived, forwards the same arguments, records the result, and returns it. A wrapper written for one fixed signature, such as wrapper(a, b), breaks the first time it decorates a function with a different one. The forwarding pair is what makes a decorator reusable across functions.
What the @ line expands to
The @ line is a shortcut for an assignment that happens right after the function is defined. Writing the assignment out by hand gives the identical result:
def announce(func):
def wrapper():
print("before")
result = func()
print("after")
return result
return wrapper
def plain():
print("hello")
return "done"
plain = announce(plain)
print(plain())
The exact output:
before
hello
after
done
The name plain first refers to the function as written, and the assignment then rebinds it to whatever announce returned. The @ form does exactly this rebinding at definition time. Two consequences follow. The decoration happens once, when the definition runs, not on every call. And the original function object still exists inside the wrapper as the stored argument, which is the only place it survives under its old behavior.
Stacked decorators apply bottom first
Two @ lines stack. The decorator closest to the function applies first, and the next one wraps the result of the first:
def star(func):
def wrapper():
return "***" + func() + "***"
return wrapper
def bracket(func):
def wrapper():
return "[" + func() + "]"
return wrapper
@star
@bracket
def word():
return "core"
print(word())
def plain():
return "core"
print(star(bracket(plain))())
The exact output:
***[core]***
***[core]***
Reading the stacked form from the bottom up matches the nested call in the second print: bracket wraps word first, then star wraps that result. The output shows the order in the characters themselves. The brackets sit against the word because bracket was applied first and runs innermost; the stars sit outside because star is the outermost wrapper: it runs first on the way in and last on the way out. Swapping the two @ lines would swap the output to [core].
A decorator that takes arguments: the factory
A plain decorator receives only the function. To configure one, such as choosing how many times to repeat a call, the decorator itself needs arguments. The pattern grows one more layer: a factory function takes the configuration, returns a decorator, and that decorator takes the function and returns the wrapper:
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
results = []
for _ in range(times):
results.append(func(*args, **kwargs))
return results
return wrapper
return decorator
@repeat(3)
def greet(name):
return "hi " + name
print(greet("bo"))
The exact output:
['hi bo', 'hi bo', 'hi bo']
The line @repeat(3) first calls repeat with 3, which returns decorator. That decorator then receives greet and returns wrapper, and the name greet is rebound to wrapper as before. Each call to greet now runs the original three times and collects the results into a list. The three layers each have one job: the factory holds the configuration, the decorator holds the function, and the wrapper holds the call arguments.
Keeping the name and docstring: functools.wraps
A wrapper replaces the original function, so by default the decorated function reports the wrapper's name and docstring instead of its own. Copying the original metadata across is a one-line fix from the functools module:
from functools import wraps
def traced(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def traced_kept(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@traced
def plain():
"""Plain docstring."""
return 1
@traced_kept
def kept():
"""Kept docstring."""
return 2
print(plain.__name__, plain.__doc__)
print(kept.__name__, kept.__doc__)
The exact output:
wrapper None
kept Kept docstring.
Without wraps, the decorated function is named wrapper and its docstring is None, because the wrapper defined none. With @wraps(func) on the wrapper, the name, docstring, and several related attributes are copied from the original, so help output, error messages, and any tool that inspects functions see the function the author wrote. Add wraps to every decorator you write. It costs one line and removes a class of confusing output where every decorated function in a program appears to have the same name.
A class-based decorator holds state
A decorator can also be a class. The class receives the function in its constructor and the instance replaces the function, so the class needs a call method to make the instance callable. State, such as a count of calls, lives on the instance:
class CountCalls:
def __init__(self, func):
self.func = func
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
return self.func(*args, **kwargs)
@CountCalls
def ping():
return "pong"
print(ping())
print(ping())
print(ping.count)
The exact output:
pong
pong
2
Each call to ping runs call, which adds one to the count and forwards to the stored function. Reading ping.count afterward reaches the instance attribute, so the total is available without a global variable. Reach for the class form when a decorator needs to keep state between calls or offer attributes the caller can read. The function form is shorter for a decorator that only adds work around each call.
Which form for which job
| Job | Form | Why |
|---|---|---|
| Add the same work around many functions | A function decorator with a forwarding wrapper | One definition; the wrapped bodies stay unchanged |
| Wrap functions with different signatures | A wrapper taking args and *kwargs | The arguments pass through untouched |
| Combine two pieces of added behavior | Stacked @ lines | They apply bottom first and each layer stays separate |
| Configure the added behavior per function | A decorator factory | The outer call holds the setting for that one use |
| Keep help and tracebacks accurate | functools.wraps on every wrapper | The original name and docstring survive |
| Count, cache, or remember across calls | A class with call | The instance holds the state between calls |
Checklist
- Before shipping a decorator, check that the wrapper returns the wrapped function's result; a missing return hands the caller None.
- Before decorating a second function, check that the wrapper signature is the forwarding pair, not the first function's parameters.
- Before stacking decorators, read them bottom up; that is the order they apply in, and the output order follows it.
- Before adding a setting to a decorator, use the factory form; do not hide configuration in a global variable.
- Before finishing any decorator, put @wraps(func) on the wrapper so the decorated function keeps its name and docstring.
- Before using a global counter for decorator state, use the class form and keep the count on the instance.
Related guides on this site
- Python Functions — def, Default Arguments, and Functions as Values — a decorator is the functions-as-values idea applied: a function passed in, and a function handed back.
- Python Generators and Iterators — yield, next, and Lazy Sequences — a wrapper around a generator function needs the same care with what the call returns.
- Python Classes and Objects — init, Methods, Inheritance, and Dataclasses — the class-based decorator uses the constructor and call method that guide covers.
- Python Loops and Conditionals — for, while, if, range, and enumerate — the repeat wrapper drives the wrapped function from an ordinary for loop.
Sources
- Python Standard Library, functools — wraps and update_wrapper, which copy a wrapped function's attributes onto the wrapper.
- Python Language Reference, Compound statements — function definitions and how decorator expressions are evaluated and applied.
- Python Glossary, decorator — the definition of a decorator and of a decorator factory.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.