Practical Implementation Examples
Real-World Scenarios for Dynamic Method Calling
1. Plugin Management System
class PluginManager:
def __init__(self):
self.plugins = {}
def register_plugin(self, name, plugin_class):
self.plugins[name] = plugin_class()
def execute_plugin(self, name, method, *args, **kwargs):
plugin = self.plugins.get(name)
if plugin and hasattr(plugin, method):
return getattr(plugin, method)(*args, **kwargs)
raise ValueError(f"Plugin {name} or method {method} not found")
## Usage example
class ImageProcessor:
def resize(self, width, height):
return f"Resized to {width}x{height}"
def convert(self, format):
return f"Converted to {format}"
manager = PluginManager()
manager.register_plugin('image', ImageProcessor)
result = manager.execute_plugin('image', 'resize', 800, 600)
2. Configuration-Driven Action Dispatcher
class ActionDispatcher:
def __init__(self, config):
self.config = config
def process_action(self, action_name, *args, **kwargs):
action_method = getattr(self, self.config.get(action_name), None)
if action_method:
return action_method(*args, **kwargs)
raise AttributeError(f"Action {action_name} not configured")
def default_action(self, *args, **kwargs):
return "Default action executed"
def advanced_action(self, *args, **kwargs):
return "Advanced action performed"
Dynamic Method Calling Patterns
graph TD
A[Dynamic Method Call] --> B{Method Validation}
B -->|Exists| C[Execute Method]
B -->|Not Found| D[Error Handling]
C --> E[Return Result]
D --> F[Fallback/Exception]
Technique |
Overhead |
Flexibility |
Use Case |
Direct Call |
Lowest |
Low |
Static Methods |
getattr() |
Medium |
High |
Runtime Selection |
Reflection |
Highest |
Very High |
Complex Dispatching |
3. Automated Testing Framework
class TestRunner:
def __init__(self, test_suite):
self.test_suite = test_suite
def run_tests(self):
results = {}
for test_name in self.test_suite:
test_method = getattr(self, test_name, None)
if callable(test_method):
try:
result = test_method()
results[test_name] = 'PASS' if result else 'FAIL'
except Exception as e:
results[test_name] = f'ERROR: {str(e)}'
return results
def test_user_creation(self):
## Simulated test logic
return True
def test_authentication(self):
## Simulated test logic
return False
Advanced Dynamic Dispatch Example
class SmartRouter:
def __init__(self):
self.routes = {
'api': self.handle_api_request,
'web': self.handle_web_request
}
def route_request(self, request_type, *args, **kwargs):
handler = self.routes.get(request_type)
return handler(*args, **kwargs) if handler else None
def handle_api_request(self, endpoint, data):
return f"API request to {endpoint} with {data}"
def handle_web_request(self, path, params):
return f"Web request to {path} with {params}"
Best Practices in Dynamic Method Calling
- Always validate method existence
- Implement robust error handling
- Use type hints for clarity
- Consider performance implications
- Document dynamic method behaviors
By exploring these practical implementation examples, developers can leverage dynamic method calling to create more flexible and adaptable Python applications in the LabEx environment.