Python Decorators Cheat Sheet
Python decorator patterns including basic function wrappers, functools.wraps, parameterized decorators, class-based decorators, and common built-in decorators.
1 PageAdvancedMar 25, 2026
Basic Decorator
A function that wraps another function's behavior.
python
def my_decorator(func): def wrapper(*args, **kwargs): print("Before call") result = func(*args, **kwargs) print("After call") return result return wrapper@my_decoratordef greet(name): print(f"Hello, {name}")greet("Alice")# Before call / Hello, Alice / After call
Preserving Metadata with functools.wraps
Keeping the wrapped function's name and docstring intact.
python
from functools import wrapsdef my_decorator(func): @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper@my_decoratordef greet(name): """Greets someone.""" return f"Hello, {name}"greet.__name__ # 'greet', not 'wrapper'greet.__doc__ # 'Greets someone.'
Decorators with Arguments
A decorator factory that accepts its own parameters.
python
from functools import wrapsdef repeat(times): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): result = None for _ in range(times): result = func(*args, **kwargs) return result return wrapper return decorator@repeat(times=3)def say_hi(): print("Hi!")say_hi() # prints Hi! three times
Class-Based Decorators
Using a class with __call__ as a stateful decorator.
python
class CountCalls: def __init__(self, func): self.func = func self.count = 0 def __call__(self, *args, **kwargs): self.count += 1 print(f"Call #{self.count}") return self.func(*args, **kwargs)@CountCallsdef hello(): print("Hello")hello() # Call #1 / Hellohello() # Call #2 / Hello
Common Built-in Decorators
Decorators provided by Python's standard library.
- @staticmethod- defines a method with no implicit self or cls argument
- @classmethod- defines a method that receives the class as its first argument
- @property- exposes a method as a read-only attribute
- @functools.lru_cache- memoizes a function's return values by its arguments
- @functools.cached_property- computes an instance property once and caches the result
- @dataclasses.dataclass- auto-generates __init__, __repr__, and __eq__ for a class
Pro Tip
Stack decorators bottom-up in your head: `@a` then `@b` above a function means `a(b(func))`, so the decorator closest to the def runs first when wrapping and last when the wrapped call actually executes.
Was this cheat sheet helpful?
Explore Topics
#PythonDecorators#PythonDecoratorsCheatSheet#Programming#Advanced#BasicDecorator#Preserving#Metadata#Functools#OOP#Functions#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance