def get_active_users(users: list[User]) -> list[User]: """Return only active users from the provided list.""" return [user for user in users if user.is_active]
# Python 3.9+ - Use built-in typesdef process_items(items: list[str]) -> dict[str, int]: return {item: len(item) for item in items}# Type aliases for complex typesJSON = Union[dict[str, Any], list[Any], str, int, float, bool, None]def parse_json(data: str) -> JSON: return json.loads(data)# Generic typesT = TypeVar('T')def first(items: list[T]) -> T | None: """Return the first item or None if list is empty.""" return items[0] if items else None
from typing import Protocolclass Renderable(Protocol): def render(self) -> str: """Render the object to a string."""def render_all(items: list[Renderable]) -> str: """Render all items that implement the Renderable protocol.""" return "\n".join(item.render() for item in items)
def load_config(path: str) -> Config: try: with open(path) as f: return Config.from_json(f.read()) except FileNotFoundError as e: raise ConfigError(f"Config file not found: {path}") from e except json.JSONDecodeError as e: raise ConfigError(f"Invalid JSON in config: {path}") from e
class AppError(Exception): """Base exception for all application errors.""" passclass ValidationError(AppError): """Raised when input validation fails.""" passclass NotFoundError(AppError): """Raised when a requested resource is not found.""" pass# Usagedef get_user(user_id: str) -> User: user = db.find_user(user_id) if not user: raise NotFoundError(f"User not found: {user_id}") return user
@dataclassclass User: email: str age: int def __post_init__(self): # Validate email format if "@" not in self.email: raise ValueError(f"Invalid email: {self.email}") # Validate age range if self.age < 0 or self.age > 150: raise ValueError(f"Invalid age: {self.age}")