Decorator Techniques
Introduction to Decorators
Decorators are a powerful Python feature that allows dynamic modification of functions or classes at runtime. They provide a clean and reusable way to extend functionality.
Types of Decorators
Decorator Type |
Description |
Use Case |
Function Decorators |
Modify function behavior |
Logging, timing, authentication |
Class Decorators |
Modify class behavior |
Singleton pattern, class registration |
Method Decorators |
Modify method behavior |
Caching, access control |
Simple Function Decorator
def performance_tracker(func):
import time
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} executed in {end_time - start_time:.4f} seconds")
return result
return wrapper
@performance_tracker
def complex_calculation(n):
return sum(i**2 for i in range(n))
complex_calculation(10000)
Decorator Composition
def bold(func):
def wrapper(*args, **kwargs):
return f"<b>{func(*args, **kwargs)}</b>"
return wrapper
def italic(func):
def wrapper(*args, **kwargs):
return f"<i>{func(*args, **kwargs)}</i>"
return wrapper
@bold
@italic
def greet(name):
return f"Hello, {name}!"
print(greet("LabEx")) ## <b><i>Hello, LabEx!</i></b>
Decorator Flow Visualization
graph TD
A[Original Function] --> B[Decorator 1]
B --> C[Decorator 2]
C --> D[Enhanced Function]
Parameterized Decorators
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(times=3)
def say_hello(name):
print(f"Hello, {name}!")
say_hello("LabEx") ## Prints greeting 3 times
Advanced Decorator Techniques
- Preserving function metadata with
functools.wraps
- Creating class decorators
- Implementing context-aware decorators
LabEx Insight
At LabEx, we recognize decorators as a sophisticated Python technique that enables elegant and modular code design.
Best Practices
- Use
functools.wraps
to preserve metadata
- Keep decorators simple and focused
- Consider performance implications
- Use decorators for cross-cutting concerns