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

More Python tasks

Back to the full Python cheat sheet