Python decorators
last modified November 30, 2026 Python 3.15
In this article we show how to write and use decorators in Python.
A decorator is a function that takes a function and returns a replacement for it. The replacement is usually a new function, called a wrapper, that runs some code before and after the original. Decorators add behaviour such as logging, timing, caching, or access checks without changing the body of the decorated function.
Decorators are built from two features covered in earlier articles: functions are objects that can be passed around (Python function), and an inner function remembers the variables of the function that created it (Python closures).
A decorator by hand
A decorator needs no special syntax. It is an ordinary function that receives a function and returns another one.
def announce(func):
def wrapper():
print("before the call")
func()
print("after the call")
return wrapper
def greet():
print("Hello there!")
greet = announce(greet)
greet()
The announce function defines an inner
wrapper that prints a line, calls the original function,
and prints another line. announce returns the wrapper
without calling it. The assignment greet = announce(greet)
replaces the name greet with the wrapper, so the next call
runs the wrapper, which in turn calls the original function through
the func variable of the closure.
$ python wrap_by_hand.py before the call Hello there! after the call
The @ syntax
Writing @decorator on the line before def is
a shorter form of the same assignment. The function is defined and
then immediately passed to the decorator.
def announce(func):
def wrapper():
print(f"calling {func.__name__}")
func()
print(f"{func.__name__} finished")
return wrapper
@announce
def greet():
print("Hello there!")
@announce
def farewell():
print("See you later!")
greet()
farewell()
The line @announce above def greet has the
same effect as greet = announce(greet) after the
definition. The same decorator is applied to two functions; each call
of announce creates a separate wrapper with its own
func. The wrapper reads func.__name__ to
print the name of the function it wraps.
$ python at_syntax.py calling greet Hello there! greet finished calling farewell See you later! farewell finished
When the decorator runs
A decorator runs once, when the def statement is executed.
The wrapper it returns runs every time the function is called.
def announce(func):
print(f"decorating {func.__name__}")
def wrapper():
print(f"calling {func.__name__}")
func()
return wrapper
print("before the definition")
@announce
def greet():
print("Hello there!")
print("after the definition")
greet()
greet()
The message decorating greet appears between the two
module-level prints, because decoration happens while the definition
is executed. The two calls only print the wrapper's message. Code that
should run once per function, such as registering it, belongs in the
decorator body; code that should run on each call belongs in the
wrapper.
$ python decoration_time.py before the definition decorating greet after the definition calling greet Hello there! calling greet Hello there!
Arguments and return values
A useful wrapper must accept any arguments the decorated function
takes and must give back its return value. The *args and
**kwargs parameters collect all positional and keyword
arguments, and the same syntax in the call passes them on.
def trace(func):
def wrapper(*args, **kwargs):
print(f"{func.__name__} args={args} kwargs={kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result!r}")
return result
return wrapper
@trace
def add(a, b):
return a + b
@trace
def welcome(name, greeting="Hello"):
return f"{greeting}, {name}!"
total = add(3, 4)
print(total * 10)
msg = welcome("Lucia", greeting="Good day")
print(msg.upper())
The trace decorator works for functions with any
signature. The wrapper prints the arguments, calls the original
function with exactly the same arguments, prints the result, and
returns it. Because the result is returned, the calling code can keep
using it: total * 10 and msg.upper() work as
if the functions were not decorated.
$ python trace_args.py
add args=(3, 4) kwargs={}
add returned 7
70
welcome args=('Lucia',) kwargs={'greeting': 'Good day'}
welcome returned 'Good day, Lucia!'
GOOD DAY, LUCIA!
Forgetting to return
A common mistake is a wrapper that calls the function but does not
return its result. The decorated function then always returns
None.
def trace(func):
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
func(*args, **kwargs)
return wrapper
@trace
def add(a, b):
return a + b
total = add(3, 4)
print(total)
The wrapper calls func(*args, **kwargs) and throws the
result away. Since wrapper has no return
statement, it returns None, and the sum computed by
add is lost. The fix is
return func(*args, **kwargs), or storing the result in a
variable and returning it at the end, as in the previous example.
$ python lost_result.py calling add None
Keeping the function metadata
After decoration, the name refers to the wrapper, so the function's
__name__ and docstring are those of the wrapper. The
functools.wraps decorator, applied to the wrapper, copies
them from the original function.
import functools
def plain(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def careful(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@plain
def area(w, h):
"""Return the area of a rectangle."""
return w * h
@careful
def volume(w, h, d):
"""Return the volume of a box."""
return w * h * d
print(area.__name__, "|", area.__doc__)
print(volume.__name__, "|", volume.__doc__)
print(volume.__wrapped__(2, 3, 4))
The plain decorator loses the metadata:
area.__name__ is wrapper and the docstring is
gone. The careful decorator uses
@functools.wraps(func), so volume keeps its
name and docstring. wraps also sets the
__wrapped__ attribute, which gives access to the original,
undecorated function. Tools such as help, debuggers, and
loggers rely on this metadata, so every decorator should use
wraps.
$ python keep_metadata.py wrapper | None volume | Return the volume of a box. 24
Measuring time
Timing is a typical job for a decorator: the measurement code is the same for every function, and it should not clutter the functions themselves.
import functools
import time
def timed(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.1f} s")
return result
return wrapper
@timed
def download(name):
time.sleep(0.3)
return f"{name}: 120 kB"
@timed
def parse(text):
time.sleep(0.1)
return text.split(": ")
data = download("report.csv")
print(parse(data))
The wrapper reads time.perf_counter before and after the
call and prints the difference rounded to tenths of a second. The two
functions simulate slow work with time.sleep. The
decorator returns the result unchanged, so the output of
download can be passed to parse.
$ python timed.py download took 0.3 s parse took 0.1 s ['report.csv', '120 kB']
Decorators with arguments
To configure a decorator, for example to say how many times to run a function, we add one more level: a function that takes the configuration and returns the actual decorator.
import functools
def repeat(times):
def decorator(func):
@functools.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 cheer(name):
print(f"Go, {name}!")
@repeat(times=2)
def ring():
print("ring")
cheer("Martin")
ring()
print(cheer.__name__, ring.__name__)
The expression repeat(3) is evaluated first. It returns
decorator, a closure that remembers times, and
this function is then applied to cheer. So
@repeat(3) means cheer = repeat(3)(cheer).
Keyword arguments work as well, as in @repeat(times=2).
Writing @repeat without the parentheses would be a bug: the
function would be passed as times.
$ python repeat.py Go, Martin! Go, Martin! Go, Martin! ring ring cheer ring
Stacking decorators
Several decorators can be applied to one function. They are applied from the bottom up, and the resulting wrappers run from the top down.
import functools
def tag(name):
def decorator(func):
print(f"wrapping {func.__name__} in <{name}>")
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"enter <{name}>")
text = func(*args, **kwargs)
print(f"leave <{name}>")
return f"<{name}>{text}</{name}>"
return wrapper
return decorator
@tag("p")
@tag("em")
def message(text):
return text
print(message("Hello there!"))
The definition is equivalent to
message = tag("p")(tag("em")(message)). The
em decorator wraps the function first, and the
p decorator wraps the result. Thanks to
wraps, the inner wrapper is still called
message when the outer decorator sees it. During the call,
the outermost wrapper is entered first and left last, so the
em tag ends up inside the p tag.
$ python stacking.py wrapping message in <em> wrapping message in <p> enter <p> enter <em> leave <em> leave <p> <p><em>Hello there!</em></p>
Registering functions
A decorator does not have to wrap the function. It can record the function somewhere and return it unchanged. This is how many frameworks map URLs, commands, or events to functions.
commands = {}
def command(name):
def decorator(func):
commands[name] = func
return func
return decorator
@command("add")
def add(a, b):
return a + b
@command("mul")
def multiply(a, b):
return a * b
@command("pow")
def power(a, b):
return a ** b
print(list(commands))
for line in ["add 2 3", "mul 4 5", "pow 2 10", "div 1 2"]:
name, a, b = line.split()
func = commands.get(name)
if func is None:
print(f"{line}: unknown command")
else:
print(f"{line} = {func(int(a), int(b))}")
print(multiply(6, 7))
The command decorator stores each function in the
commands dictionary under the given name and returns the
same function object. The input lines are then dispatched by looking up
the command name. Because no wrapper is involved, the functions can
still be called directly and run at full speed, as the last line shows.
Web frameworks use the same idea, for example Flask's
@app.route("/").
$ python registry.py ['add', 'mul', 'pow'] add 2 3 = 5 mul 4 5 = 20 pow 2 10 = 1024 div 1 2: unknown command 42
Retrying a failing call
A wrapper can catch exceptions raised by the decorated function. A retry decorator calls the function again when it fails with a temporary error.
import functools
def retry(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return func(*args, **kwargs)
except ConnectionError as e:
print(f"attempt {attempt} failed: {e}")
raise ConnectionError(f"{func.__name__} failed {times} times")
return wrapper
return decorator
replies = ["timeout", "timeout", "data", "timeout", "timeout", "timeout"]
@retry(times=3)
def fetch():
reply = replies.pop(0)
if reply == "timeout":
raise ConnectionError("timed out")
return reply
print(fetch())
try:
fetch()
except ConnectionError as e:
print("giving up:", e)
The wrapper calls the function up to times times. A
successful call returns immediately; a ConnectionError is
reported and the loop tries again. When all attempts fail, the wrapper
raises a new exception. The fetch function takes its
replies from a list to simulate a server that times out: the first call
succeeds on the third attempt, the second call fails three times and
gives up.
$ python retry.py attempt 1 failed: timed out attempt 2 failed: timed out data attempt 1 failed: timed out attempt 2 failed: timed out attempt 3 failed: timed out giving up: fetch failed 3 times
Decorators in the standard library
The standard library provides ready-made decorators. The
functools.cache decorator stores the results of a function
and returns the stored value when the function is called again with
the same arguments.
import functools
@functools.cache
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(80))
print(fib.cache_info())
print(fib(90))
print(fib.cache_info())
fib.cache_clear()
print(fib.cache_info())
Without the cache, the recursive fib(80) would make an
astronomical number of calls. With it, each value is computed once:
cache_info shows 81 misses, one for each of the values
from 0 to 80. Calling fib(90) later computes only the ten
new values. cache_clear empties the cache. Other common
decorators are @staticmethod, @classmethod,
and @property for methods, and @dataclass,
which is applied to a whole class.
$ python std_cache.py 23416728348467685 CacheInfo(hits=78, misses=81, maxsize=None, currsize=81) 2880067194370816120 CacheInfo(hits=89, misses=91, maxsize=None, currsize=91) CacheInfo(hits=0, misses=0, maxsize=None, currsize=0)
Source
Glossary: decorator, Function definitions, functools.wraps, PEP 318 – Decorators for functions and methods
In this article we have written decorators by hand and with the
@ syntax, passed arguments and return values through
wrappers, kept function metadata with functools.wraps,
measured time, written decorators with arguments, stacked them,
registered functions, retried failing calls, and used
functools.cache. Decorators written as classes are covered
in Python callable objects; decorators
for methods appear in
Python static methods and
Python property decorator. See
also Python closures.
Author
List all Python tutorials.