Decorators
More Python10 min readLesson 3 of 7
3.1 A function that takes a function
Functions are values in Python, so a wrapper function can accept another function, define an inner function, and return it. The @decorator syntax is shorthand: the name below is replaced by the decorated version.
Always copy the wrapped function's metadata with functools.wraps. Without it, the decorated function keeps the wrapper's name and docstring, which confuses tracebacks, documentation and tools that inspect signatures.
from functools import wraps
def log_calls(function):
@wraps(function)
def wrapper(*args, **kwargs):
print("calling", function.__name__)
return function(*args, **kwargs)
return wrapper
@log_calls
def add(a, b):
return a + b
print(add(2, 3))Output
calling add 5
Decorators are common for logging, timing, retries, permissions and caching (functools.lru_cache). Keep them small and preserve the signature with *args, **kwargs so the wrapper works for any function.
