Here's an advanced Python code example that demonstrates various sophisticated concepts including async programming, metaclasses, decorators, type hints, context managers, and design patterns. This is a complex example of a distributed task processing system:
python
from __future__ import annotations
from typing import TypeVar, Generic, Callable, Any, Optional, Dict, List, Union
import asyncio
import functools
import inspect
import logging
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager, asynccontextmanager
# Type variables
T = TypeVar('T')
R = TypeVar('R')
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Metaclass for singleton pattern
class Singleton(type):
_instances: Dict[type, Any] = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
# Decorator for timing functions
def timing_decorator(func: Callable) -> Callable:
@functools.wraps(func)
async def wrapper(*args, **kwargs):
start_time = time.perf_counter()
result = await func(*args, **kwargs) if inspect.iscoroutinefunction(func) else func(*args, **kwargs)
end_time = time.perf_counter()
logger.info(f"{func.__name__} took {end_time - start_time:.2f} seconds")
return result
return wrapper
# Abstract base class for task processing
class TaskProcessor(ABC, Generic[T, R]):
@abstractmethod
async def process(self, task: T) -> R:
pass
# Task result container
@dataclass
class TaskResult(Generic[R]):
result: R
processing_time: float
task_id: str
# Task Queue Manager
class TaskQueueManager(metaclass=Singleton):
def __init__(self):
self.tasks: asyncio.Queue = asyncio.Queue()
self.results: Dict[str, TaskResult] = {}
self.executor = ThreadPoolExecutor(max_workers=4)
self._running = False
async def submit_task(self, task: T) -> str:
task_id = str(id(task))
await self.tasks.put((task_id, task))
return task_id
async def get_result(self, task_id: str) -> Optional[TaskResult]:
return self.results.get(task_id)
@timing_decorator
async def process_tasks(self, processor: TaskProcessor[T, R]):
self._running = True
while self._running:
try:
task_id, task = await self.tasks.get()
start_time = time.perf_counter()
# Process task
result = await processor.process(task)
# Store result
processing_time = time.perf_counter() - start_time
self.results[task_id] = TaskResult(
result=result,
processing_time=processing_time,
task_id=task_id
)
self.tasks.task_done()
except Exception as e:
logger.error(f"Error processing task: {e}")
def stop(self):
self._running = False
# Context manager for task queue
@contextmanager
def task_queue_context():
queue_manager = TaskQueueManager()
try:
yield queue_manager
finally:
queue_manager.stop()
queue_manager.executor.shutdown()
# Example task processor implementation
class ImageProcessor(TaskProcessor[str, Dict[str, Any]]):
async def process(self, task: str) -> Dict[str, Any]:
# Simulate image processing
await asyncio.sleep(1)
return {"processed": task, "timestamp": time.time()}
# Example usage
async def main():
async with asyncio.TaskGroup() as tg:
with task_queue_context() as queue_manager:
# Create processor
processor = ImageProcessor()
# Start processing tasks
processor_task = tg.create_task(queue_manager.process_tasks(processor))
# Submit tasks
tasks = ["image1.jpg", "image2.jpg", "image3.jpg"]
task_ids = []
for task in tasks:
task_id = await queue_manager.submit_task(task)
task_ids.append(task_id)
# Wait for results
results = []
for task_id in task_ids:
while True:
result = await queue_manager.get_result(task_id)
if result:
results.append(result)
break
await asyncio.sleep(0.1)
# Print results
for result in results:
logger.info(f"Task {result.task_id}: {result.result}")
logger.info(f"Processing time: {result.processing_time:.2f} seconds")
# Run the example
if __name__ == "__main__":
asyncio.run(main())
This code demonstrates several advanced Python features and concepts:
Type Hints and Generics: Using Python's typing system for better code documentation and IDE support.
Metaclasses: Implementation of the Singleton pattern using a metaclass.
Async/Await: Asynchronous programming with modern Python async features.
Decorators: Custom timing decorator for performance monitoring.
Context Managers: Both regular and async context managers for resource management.
Abstract Base Classes: Using ABC for defining interfaces.
Dataclasses: Using Python's dataclass feature for clean data containers.
Generic Type Variables: Implementing generic types for flexibility and type safety.
Thread Pool Executor: Integration with concurrent.futures for parallel processing.
Error Handling: Proper exception handling and logging.
Task Queue Management: Implementing a task queue system with async capabilities.
Design Patterns: Implementation of Singleton and Producer-Consumer patterns.
This code could be extended further with:
Persistent storage for tasks and results
Network communication for distributed processing
More sophisticated error handling and retry mechanisms
Monitoring and metrics collection
Rate limiting and backpressure handling
Task prioritization
Advanced cancellation handling
The code is designed to be maintainable, scalable, and follows many Python best practices and modern programming paradigms.