Wrap behaviour, keep the name.
Add a reusable boundary around a function without losing its identity.
01 The idea
A decorator accepts a callable and returns a callable, commonly to add behaviour before or after a call. The @ syntax applies that transformation at definition time. A careful wrapper forwards positional and keyword arguments, returns the underlying result, and preserves metadata using functools.wraps.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from functools import wraps
def announce(function):
@wraps(function)
def wrapped(*args, **kwargs):
print(f"Running {function.__name__}")
return function(*args, **kwargs)
return wrapped
@announce
def add(a, b):
return a + b
print(add(2, b=5))
print(add.__name__)Running add 7 add
03 Under the hood
- 1
@announce is the readable equivalent of add = announce(add) after defining the original function.
- 2
The wrapper forwards both kinds of arguments. Returning the result matters: a wrapper that merely calls function would make every decorated call return None.
- 3
wraps copies metadata and sets __wrapped__, helping documentation and introspection. This synchronous wrapper is not suitable unchanged for an async function; asynchronous wrappers must await their underlying coroutine.
04 Your turn, builder
Write a decorator that doubles a numeric return value while preserving metadata.
Reveal one possible solution +
from functools import wraps
def doubled(function):
@wraps(function)
def wrapped(*args, **kwargs):
return 2 * function(*args, **kwargs)
return wrapped
@doubled
def total(a, b):
return a + b
print(total(3, 4))05 Check your signal
Why use wraps in a decorator?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.