Advanced Use Cases
Complex Scenarios with Class Method Decorators
1. Dynamic Configuration Management
class ConfigManager:
_config = {}
@classmethod
def register_config(cls, key, default=None):
def decorator(func):
cls._config[key] = default
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorator
@classmethod
def get_config(cls, key):
return cls._config.get(key)
Workflow of Dynamic Configuration
graph TD
A[Define Configuration] --> B[Register with Decorator]
B --> C[Access Configuration]
C --> D[Retrieve or Use Default Value]
2. Singleton Pattern Implementation
class SingletonMeta(type):
_instances = {}
@classmethod
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class DatabaseConnection(metaclass=SingletonMeta):
@classmethod
def get_connection(cls):
return cls()
Advanced Decorator Patterns
Pattern |
Description |
Key Benefit |
Singleton |
Ensure single instance |
Resource management |
Configuration |
Dynamic setting management |
Flexible configuration |
Validation |
Complex input checking |
Data integrity |
3. Comprehensive Validation Decorator
class ValidationDecorator:
@classmethod
def validate_input(cls, validator):
def decorator(method):
def wrapper(cls, *args, **kwargs):
if not validator(*args, **kwargs):
raise ValueError("Invalid input")
return method(cls, *args, **kwargs)
return wrapper
return decorator
class DataProcessor:
@ValidationDecorator.validate_input(
lambda x: isinstance(x, list) and len(x) > 0
)
@classmethod
def process_data(cls, data):
return [item.strip() for item in data]
- Minimize decorator complexity
- Use caching for expensive operations
- Implement proper error handling
Real-world Application Patterns
Dependency Injection
class ServiceContainer:
_services = {}
@classmethod
def register_service(cls, service_type, service_impl):
cls._services[service_type] = service_impl
@classmethod
def get_service(cls, service_type):
return cls._services.get(service_type)
Best Practices
- Keep decorators focused
- Minimize performance overhead
- Provide clear error messages
- Use type hints for clarity
At LabEx, we believe mastering advanced class method decorators enables more robust and flexible Python programming.