A wrapper calls another function while adding behavior around the call. A decorator receives a function and returns a replacement, often a wrapper. It uses the same higher-order functions and closures we already saw.
from functools import wraps
def announce(function):
@wraps(function)
def wrapper(*args, **kwargs):
print("Calling", function.__name__)
return function(*args, **kwargs)
return wrapper
@announce
def area(width, height=1):
return width * height
print(area(3, height=4))
print(area.__name__)
Calling area
12
area
When the definition executes, @announce has the effect of assigning area = announce(area). Later calls enter wrapper, which calls the original. The wrapper retains function as a closure and returns its result. Printing is an effect of the wrapper, even though the calculation itself is pure.
In a definition, *args collects positional arguments into a tuple and **kwargs collects keyword arguments into a dictionary. In function(*args, **kwargs) they unpack them again. The original still enforces its own argument rules. wraps preserves metadata such as the original name and exposes __wrapped__; it does not make a wrapper pure or guarantee its behavior. An exception from the original propagates unless caught.
A decorator factory supplies configuration before decoration. For two decorators, application is bottom-up but calls enter the outer wrapper first:
def add_before(amount):
def decorate(function):
def wrapper(value):
return function(value + amount)
return wrapper
return decorate
def double_before(function):
def wrapper(value):
return function(value * 2)
return wrapper
@add_before(3)
@double_before
def identity(value):
return value
print(identity(4))
14
The assignment is identity = add_before(3)(double_before(identity)). Calling it sends 4 through addition first, then doubling: 4 → 7 → 14. Reversing the wrappers gives 11. Use wrappers where the shared behavior is worth the extra indirection.