Loading workspace environment...
Design production-ready Python services with strict Type Hints (PEP 484), dependency injection, structured logging, configuration validation, and unit testing patterns.
from typing import Protocol, Optional, List, DictAdvanced structural subtyping and generic annotations.import loggingStandard library structured logging framework.from typing import Protocol, Dict, Optional
class User:
def __init__(self, user_id: str, email: str):
self.user_id = user_id
self.email = email
class UserRepository(Protocol):
def get_by_id(self, user_id: str) -> Optional[User]: ...
def save(self, user: User) -> None: ...
class InMemoryUserRepository:
def __init__(self) -> None:
self._storage: Dict[str, User] = {}
def get_by_id(self, user_id: str) -> Optional[User]:
return self._storage.get(user_id)
def save(self, user: User) -> None:
self._storage[user.user_id] = user
class UserService:
def __init__(self, repo: UserRepository) -> None:
self.repo = repo
def register_user(self, user_id: str, email: str) -> User:
existing = self.repo.get_by_id(user_id)
if existing:
raise ValueError(f"User {user_id} already exists")
user = User(user_id=user_id, email=email)
self.repo.save(user)
return user
repo = InMemoryUserRepository()
service = UserService(repo)
user = service.register_user("u101", "developer@google.com")
print(f"Registered user: {user.user_id} <{user.email}>")
retrieved = repo.get_by_id("u101")
print(f"Verified in repository: {retrieved is not None}")Registered user: u101 <developer@google.com>
Verified in repository: Trueprint("Error occurred in database")import logging
logging.error("Failed to connect to database", exc_info=True)Architectural Explanation: Never use print() for production logging. Use the logging module to capture timestamps, severity levels, and stack traces.