""" Base classes for command pattern implementation. """ from abc import ABC, abstractmethod from typing import Any, Dict, List, Optional, TypeVar, Generic, Union # Type variable for the result of a command T = TypeVar('T') class Command(ABC): """ Base abstract class for all commands. Commands encapsulate business logic and ensure data integrity. """ @abstractmethod def execute(self) -> Any: """ Execute the command and return the result. Must be implemented by all command subclasses. Returns: Any: The result of the command execution. """ pass def validate(self) -> Dict[str, Any]: """ Validate command data before execution. Should be overridden by command subclasses. Returns: Dict[str, Any]: Validation result with 'is_valid' and optional 'errors'. """ return {'is_valid': True, 'errors': None} class CommandResult(Generic[T]): """ Represents the result of a command execution. Attributes: success (bool): Whether the command was successful. data (Optional[T]): The result data, if successful. errors (Optional[List[str]]): List of errors, if unsuccessful. message (Optional[str]): An optional message about the operation. """ def __init__( self, success: bool = True, data: Optional[T] = None, errors: Optional[List[str]] = None, message: Optional[str] = None ): """ Initialize a new CommandResult. Args: success: Whether the command was successful. data: The result data, if successful. errors: List of errors, if unsuccessful. message: An optional message about the operation. """ self.success = success self.data = data self.errors = errors or [] self.message = message def to_dict(self) -> Dict[str, Any]: """ Convert the command result to a dictionary. Returns: Dict[str, Any]: The command result as a dictionary. """ return { 'success': self.success, 'data': self.data, 'errors': self.errors, 'message': self.message } @classmethod def success_result(cls, data: T = None, message: Optional[str] = None) -> 'CommandResult[T]': """ Create a successful command result. Args: data: The result data. message: An optional success message. Returns: CommandResult[T]: A successful command result. """ return cls(True, data, None, message) @classmethod def failure_result(cls, errors: Union[str, List[str]], message: Optional[str] = None) -> 'CommandResult[T]': """ Create a failed command result. Args: errors: Error or list of errors. message: An optional failure message. Returns: CommandResult[T]: A failed command result. """ if isinstance(errors, str): errors = [errors] return cls(False, None, errors, message)