Sub topic 1
Python Decorators: Wrapping Functions to Add Behavior
Prerequisites
This chapter assumes you can define and call Python functions, use positional and keyword arguments, write basic classes, and import standard-library modules.
Functions are objects you can pass around
In Python, a function is an object. You can store it in a variable, pass it to another function, or return it from a function. Calling it still requires parentheses.
def make_multiplier(n):
def multiply(x):
return x * n
return multiply
double = make_multiplier(2)
def apply_twice(func, value):
return func(func(value))
print(double(5)) # 10
print(apply_twice(double, 3)) # 12double refers to the function returned by make_multiplier. apply_twice accepts that function as an argument.
Nested functions and closures
A nested function is a function defined inside another function. A closure is a nested function that remembers variables from its enclosing function after the enclosing function has returned.
Here, multiply remembers n. Each call to make_multiplier can create a closure with a different remembered value.
Forwarding arguments with *args and **kwargs
A decorator usually needs to accept whatever arguments the original function accepts. *args collects positional arguments into a tuple. **kwargs collects keyword arguments into a dictionary.
The wrapper can forward both collections with func(*args, **kwargs). This lets one decorator work with many function signatures.
Your first decorator
A decorator is a function that receives another function, adds behavior, and returns a replacement function.
import functools
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
result = func(*args, **kwargs)
print(f"Returned {result!r}")
return result
return wrapper
@timer
def add(a, b):
return a + b
print(add(2, b=3))wrapper forwards the arguments and returns the original result. functools.wraps preserves metadata such as the original function's name and docstring.
Exercise
What does @timer do to add?
Show answer
It replaces add with the wrapper returned by timer(add).