Common Decorators
Decorators are powerful tools in Python that allow you to modify or enhance functions without directly changing their source code. The functools module provides several built-in decorators to simplify function manipulation.
graph TD
A[Functools Decorators] --> B[@wraps]
A --> C[@lru_cache]
A --> D[@total_ordering]
A --> E[@singledispatch]
@wraps Decorator
The @wraps decorator helps preserve metadata of the original function when creating wrapper functions.
from functools import wraps
def log_function_call(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling function: {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_function_call
def add(x, y):
return x + y
print(add(3, 4)) ## Preserves original function metadata
@lru_cache Decorator
Implements memoization to cache function results and improve performance.
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(100)) ## Efficient recursive calculation
Decorator Comparison
| Decorator |
Purpose |
Use Case |
@wraps |
Preserve function metadata |
Creating custom decorators |
@lru_cache |
Caching function results |
Optimizing recursive functions |
@total_ordering |
Generate comparison methods |
Simplifying class comparisons |
@singledispatch |
Method overloading |
Handling different input types |
@total_ordering Decorator
Automatically generates comparison methods for classes.
from functools import total_ordering
@total_ordering
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.age == other.age
def __lt__(self, other):
return self.age < other.age
p1 = Person("Alice", 30)
p2 = Person("Bob", 25)
print(p1 > p2) ## Automatically generated comparison
LabEx Practical Insight
LabEx recommends mastering these decorators to write more efficient and clean Python code. Practice and experimentation are key to understanding their full potential.
Best Practices
- Use decorators to separate concerns
- Avoid overusing decorators
- Understand the performance implications
- Preserve original function metadata