Decorators in Python
From the Python cheat sheet ยท Advanced Features ยท verified Jul 2026
Decorators
Wrap functions to add behavior without modifying the original.
python
import functools
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__}: {time.time()-start:.2f}s")
return result
return wrapper
@timer
def slow_function():
import time; time.sleep(1)๐ก Always use @functools.wraps(func) to preserve the original function's metadata
โก @functools.lru_cache is a built-in memoization decorator โ use it for expensive calls
๐ Stacked decorators apply bottom-up: the lowest decorator wraps first
๐ข The @decorator syntax is shorthand for: func = decorator(func)
decoratorsadvanced