[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M72XVMMPA2B3ERQQX90MDC3V":3,"skill-same:01M72XVMMPA2B3ERQQX90MDC3V":45},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":23,"commitSha":24,"skillDirectory":25,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":28,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M72XVMMPA2B3ERQQX90MDC3V","python-design-patterns",null,"Python design patterns including KISS, Separation of Concerns, Single Responsibility, and composition over inheritance. Use this skill when designing a new service or component from scratch and choosing how to layer responsibilities, when refactoring a God class or monolithic function that has grown too large, when deciding whether to add a new abstraction or live with duplication, when evaluating a pull request for structural issues like tight coupling or leaking internal types, when choosing between inheritance and composition for a new class hierarchy, or when a codebase is becoming hard to test because of entangled I\u002FO and business logic.","steph-frtech\u002Fclaude-code-up","steph-frtech","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F198466323?v=4","01M72XD213FVQA2QXRGTJFKHE1","01M72XD227AANJ993SQTNZB1CK",1,"MIT","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fpython-development\u002Fskills\u002Fpython-design-patterns\u002FSKILL.md",[],[],"2026-11-10 22:39:42",false,"---\nname: python-design-patterns\ndescription: Python design patterns including KISS, Separation of Concerns, Single Responsibility, and composition over inheritance. Use this skill when designing a new service or component from scratch and choosing how to layer responsibilities, when refactoring a God class or monolithic function that has grown too large, when deciding whether to add a new abstraction or live with duplication, when evaluating a pull request for structural issues like tight coupling or leaking internal types, when choosing between inheritance and composition for a new class hierarchy, or when a codebase is becoming hard to test because of entangled I\u002FO and business logic.\n---\n\n# Python Design Patterns\n\nWrite maintainable Python code using fundamental design principles. These patterns help you build systems that are easy to understand, test, and modify.\n\n## When to Use This Skill\n\n- Designing new components or services\n- Refactoring complex or tangled code\n- Deciding whether to create an abstraction\n- Choosing between inheritance and composition\n- Evaluating code complexity and coupling\n- Planning modular architectures\n\n## Core Concepts\n\n### 1. KISS (Keep It Simple)\n\nChoose the simplest solution that works. Complexity must be justified by concrete requirements.\n\n### 2. Single Responsibility (SRP)\n\nEach unit should have one reason to change. Separate concerns into focused components.\n\n### 3. Composition Over Inheritance\n\nBuild behavior by combining objects, not extending classes.\n\n### 4. Rule of Three\n\nWait until you have three instances before abstracting. Duplication is often better than premature abstraction.\n\n## Quick Start\n\n```python\n# Simple beats clever\n# Instead of a factory\u002Fregistry pattern:\nFORMATTERS = {\"json\": JsonFormatter, \"csv\": CsvFormatter}\n\ndef get_formatter(name: str) -> Formatter:\n    return FORMATTERS[name]()\n```\n\n## Fundamental Patterns\n\n### Pattern 1: KISS - Keep It Simple\n\nBefore adding complexity, ask: does a simpler solution work?\n\n```python\n# Over-engineered: Factory with registration\nclass OutputFormatterFactory:\n    _formatters: dict[str, type[Formatter]] = {}\n\n    @classmethod\n    def register(cls, name: str):\n        def decorator(formatter_cls):\n            cls._formatters[name] = formatter_cls\n            return formatter_cls\n        return decorator\n\n    @classmethod\n    def create(cls, name: str) -> Formatter:\n        return cls._formatters[name]()\n\n@OutputFormatterFactory.register(\"json\")\nclass JsonFormatter(Formatter):\n    ...\n\n# Simple: Just use a dictionary\nFORMATTERS = {\n    \"json\": JsonFormatter,\n    \"csv\": CsvFormatter,\n    \"xml\": XmlFormatter,\n}\n\ndef get_formatter(name: str) -> Formatter:\n    \"\"\"Get formatter by name.\"\"\"\n    if name not in FORMATTERS:\n        raise ValueError(f\"Unknown format: {name}\")\n    return FORMATTERS[name]()\n```\n\nThe factory pattern adds code without adding value here. Save patterns for when they solve real problems.\n\n### Pattern 2: Single Responsibility Principle\n\nEach class or function should have one reason to change.\n\n```python\n# BAD: Handler does everything\nclass UserHandler:\n    async def create_user(self, request: Request) -> Response:\n        # HTTP parsing\n        data = await request.json()\n\n        # Validation\n        if not data.get(\"email\"):\n            return Response({\"error\": \"email required\"}, status=400)\n\n        # Database access\n        user = await db.execute(\n            \"INSERT INTO users (email, name) VALUES ($1, $2) RETURNING *\",\n            data[\"email\"], data[\"name\"]\n        )\n\n        # Response formatting\n        return Response({\"id\": user.id, \"email\": user.email}, status=201)\n\n# GOOD: Separated concerns\nclass UserService:\n    \"\"\"Business logic only.\"\"\"\n\n    def __init__(self, repo: UserRepository) -> None:\n        self._repo = repo\n\n    async def create_user(self, data: CreateUserInput) -> User:\n        # Only business rules here\n        user = User(email=data.email, name=data.name)\n        return await self._repo.save(user)\n\nclass UserHandler:\n    \"\"\"HTTP concerns only.\"\"\"\n\n    def __init__(self, service: UserService) -> None:\n        self._service = service\n\n    async def create_user(self, request: Request) -> Response:\n        data = CreateUserInput(**(await request.json()))\n        user = await self._service.create_user(data)\n        return Response(user.to_dict(), status=201)\n```\n\nNow HTTP changes don't affect business logic, and vice versa.\n\n### Pattern 3: Separation of Concerns\n\nOrganize code into distinct layers with clear responsibilities.\n\n```\n┌─────────────────────────────────────────────────────┐\n│  API Layer (handlers)                                │\n│  - Parse requests                                    │\n│  - Call services                                     │\n│  - Format responses                                  │\n└─────────────────────────────────────────────────────┘\n                        │\n                        ▼\n┌─────────────────────────────────────────────────────┐\n│  Service Layer (business logic)                      │\n│  - Domain rules and validation                       │\n│  - Orchestrate operations                            │\n│  - Pure functions where possible                     │\n└─────────────────────────────────────────────────────┘\n                        │\n                        ▼\n┌─────────────────────────────────────────────────────┐\n│  Repository Layer (data access)                      │\n│  - SQL queries                                       │\n│  - External API calls                                │\n│  - Cache operations                                  │\n└─────────────────────────────────────────────────────┘\n```\n\nEach layer depends only on layers below it:\n\n```python\n# Repository: Data access\nclass UserRepository:\n    async def get_by_id(self, user_id: str) -> User | None:\n        row = await self._db.fetchrow(\n            \"SELECT * FROM users WHERE id = $1\", user_id\n        )\n        return User(**row) if row else None\n\n# Service: Business logic\nclass UserService:\n    def __init__(self, repo: UserRepository) -> None:\n        self._repo = repo\n\n    async def get_user(self, user_id: str) -> User:\n        user = await self._repo.get_by_id(user_id)\n        if user is None:\n            raise UserNotFoundError(user_id)\n        return user\n\n# Handler: HTTP concerns\n@app.get(\"\u002Fusers\u002F{user_id}\")\nasync def get_user(user_id: str) -> UserResponse:\n    user = await user_service.get_user(user_id)\n    return UserResponse.from_user(user)\n```\n\n### Pattern 4: Composition Over Inheritance\n\nBuild behavior by combining objects rather than inheriting.\n\n```python\n# Inheritance: Rigid and hard to test\nclass EmailNotificationService(NotificationService):\n    def __init__(self):\n        super().__init__()\n        self._smtp = SmtpClient()  # Hard to mock\n\n    def notify(self, user: User, message: str) -> None:\n        self._smtp.send(user.email, message)\n\n# Composition: Flexible and testable\nclass NotificationService:\n    \"\"\"Send notifications via multiple channels.\"\"\"\n\n    def __init__(\n        self,\n        email_sender: EmailSender,\n        sms_sender: SmsSender | None = None,\n        push_sender: PushSender | None = None,\n    ) -> None:\n        self._email = email_sender\n        self._sms = sms_sender\n        self._push = push_sender\n\n    async def notify(\n        self,\n        user: User,\n        message: str,\n        channels: set[str] | None = None,\n    ) -> None:\n        channels = channels or {\"email\"}\n\n        if \"email\" in channels:\n            await self._email.send(user.email, message)\n\n        if \"sms\" in channels and self._sms and user.phone:\n            await self._sms.send(user.phone, message)\n\n        if \"push\" in channels and self._push and user.device_token:\n            await self._push.send(user.device_token, message)\n\n# Easy to test with fakes\nservice = NotificationService(\n    email_sender=FakeEmailSender(),\n    sms_sender=FakeSmsSender(),\n)\n```\n\n## Advanced Patterns\n\n### Pattern 5: Rule of Three\n\nWait until you have three instances before abstracting.\n\n```python\n# Two similar functions? Don't abstract yet\ndef process_orders(orders: list[Order]) -> list[Result]:\n    results = []\n    for order in orders:\n        validated = validate_order(order)\n        result = process_validated_order(validated)\n        results.append(result)\n    return results\n\ndef process_returns(returns: list[Return]) -> list[Result]:\n    results = []\n    for ret in returns:\n        validated = validate_return(ret)\n        result = process_validated_return(validated)\n        results.append(result)\n    return results\n\n# These look similar, but wait! Are they actually the same?\n# Different validation, different processing, different errors...\n# Duplication is often better than the wrong abstraction\n\n# Only after a third case, consider if there's a real pattern\n# But even then, sometimes explicit is better than abstract\n```\n\n### Pattern 6: Function Size Guidelines\n\nKeep functions focused. Extract when a function:\n\n- Exceeds 20-50 lines (varies by complexity)\n- Serves multiple distinct purposes\n- Has deeply nested logic (3+ levels)\n\n```python\n# Too long, multiple concerns mixed\ndef process_order(order: Order) -> Result:\n    # 50 lines of validation...\n    # 30 lines of inventory check...\n    # 40 lines of payment processing...\n    # 20 lines of notification...\n    pass\n\n# Better: Composed from focused functions\ndef process_order(order: Order) -> Result:\n    \"\"\"Process a customer order through the complete workflow.\"\"\"\n    validate_order(order)\n    reserve_inventory(order)\n    payment_result = charge_payment(order)\n    send_confirmation(order, payment_result)\n    return Result(success=True, order_id=order.id)\n```\n\n### Pattern 7: Dependency Injection\n\nPass dependencies through constructors for testability.\n\n```python\nfrom typing import Protocol\n\nclass Logger(Protocol):\n    def info(self, msg: str, **kwargs) -> None: ...\n    def error(self, msg: str, **kwargs) -> None: ...\n\nclass Cache(Protocol):\n    async def get(self, key: str) -> str | None: ...\n    async def set(self, key: str, value: str, ttl: int) -> None: ...\n\nclass UserService:\n    \"\"\"Service with injected dependencies.\"\"\"\n\n    def __init__(\n        self,\n        repository: UserRepository,\n        cache: Cache,\n        logger: Logger,\n    ) -> None:\n        self._repo = repository\n        self._cache = cache\n        self._logger = logger\n\n    async def get_user(self, user_id: str) -> User:\n        # Check cache first\n        cached = await self._cache.get(f\"user:{user_id}\")\n        if cached:\n            self._logger.info(\"Cache hit\", user_id=user_id)\n            return User.from_json(cached)\n\n        # Fetch from database\n        user = await self._repo.get_by_id(user_id)\n        if user:\n            await self._cache.set(f\"user:{user_id}\", user.to_json(), ttl=300)\n\n        return user\n\n# Production\nservice = UserService(\n    repository=PostgresUserRepository(db),\n    cache=RedisCache(redis),\n    logger=StructlogLogger(),\n)\n\n# Testing\nservice = UserService(\n    repository=InMemoryUserRepository(),\n    cache=FakeCache(),\n    logger=NullLogger(),\n)\n```\n\n### Pattern 8: Avoiding Common Anti-Patterns\n\n**Don't expose internal types:**\n\n```python\n# BAD: Leaking ORM model to API\n@app.get(\"\u002Fusers\u002F{id}\")\ndef get_user(id: str) -> UserModel:  # SQLAlchemy model\n    return db.query(UserModel).get(id)\n\n# GOOD: Use response schemas\n@app.get(\"\u002Fusers\u002F{id}\")\ndef get_user(id: str) -> UserResponse:\n    user = db.query(UserModel).get(id)\n    return UserResponse.from_orm(user)\n```\n\n**Don't mix I\u002FO with business logic:**\n\n```python\n# BAD: SQL embedded in business logic\ndef calculate_discount(user_id: str) -> float:\n    user = db.query(\"SELECT * FROM users WHERE id = ?\", user_id)\n    orders = db.query(\"SELECT * FROM orders WHERE user_id = ?\", user_id)\n    # Business logic mixed with data access\n\n# GOOD: Repository pattern\ndef calculate_discount(user: User, order_history: list[Order]) -> float:\n    # Pure business logic, easily testable\n    if len(order_history) > 10:\n        return 0.15\n    return 0.0\n```\n\n## Best Practices Summary\n\n1. **Keep it simple** - Choose the simplest solution that works\n2. **Single responsibility** - Each unit has one reason to change\n3. **Separate concerns** - Distinct layers with clear purposes\n4. **Compose, don't inherit** - Combine objects for flexibility\n5. **Rule of three** - Wait before abstracting\n6. **Keep functions small** - 20-50 lines (varies by complexity), one purpose\n7. **Inject dependencies** - Constructor injection for testability\n8. **Delete before abstracting** - Remove dead code, then consider patterns\n9. **Test each layer** - Isolated tests for each concern\n10. **Explicit over clever** - Readable code beats elegant code\n\n## Troubleshooting\n\n**A class is growing and seems to have multiple responsibilities, but splitting it feels wrong.**\nApply the \"reason to change\" test: list every change that could require editing this class. If the list has items from different domains (e.g., HTTP parsing AND business rules AND formatting), split it. If all changes stem from the same domain concern, the class may be appropriately sized.\n\n**Injecting all dependencies through the constructor is producing constructors with 7+ parameters.**\nThis is a sign of too many responsibilities in one class, not a problem with dependency injection. Split the class into smaller units first, then each constructor naturally becomes smaller.\n\n**Composition is producing deeply nested wrapper objects that are hard to trace.**\nKeep the composition shallow (2-3 levels). If wrapping is the only mechanism, consider whether a Protocol-based approach or simple function composition would be cleaner than a chain of decorator objects.\n\n**The rule of three says not to abstract yet, but the duplication is causing bugs when one copy is updated but not the other.**\nDuplication that diverges in dangerous ways should be abstracted sooner. The rule of three is a heuristic, not a law. If the copies are already diverging incorrectly, extract immediately and add a test that exercises the shared behavior.\n\n**A service layer is importing from the API layer, breaking the dependency direction.**\nThis is a layering violation. The service layer must not import from handlers. Introduce a shared types\u002Fmodels layer that both can import from, keeping the dependency arrow pointing downward (API → Service → Repository).\n\n## Related Skills\n\n- [python-testing-patterns](..\u002Fpython-testing-patterns\u002FSKILL.md) — Test each layer in isolation using the dependency injection structure established here\n- [python-project-setup](..\u002Fpython-project-setup\u002FSKILL.md) — Set up project structure and tooling that enforces layer boundaries from the start\n","# Python Design Patterns\n\nWrite maintainable Python code using fundamental design principles. These patterns help you build systems that are easy to understand, test, and modify.\n\n## When to Use This Skill\n\n- Designing new components or services\n- Refactoring complex or tangled code\n- Deciding whether to create an abstraction\n- Choosing between inheritance and composition\n- Evaluating code complexity and coupling\n- Planning modular architectures\n\n## Core Concepts\n\n### 1. KISS (Keep It Simple)\n\nChoose the simplest solution that works. Complexity must be justified by concrete requirements.\n\n### 2. Single Responsibility (SRP)\n\nEach unit should have one reason to change. Separate concerns into focused components.\n\n### 3. Composition Over Inheritance\n\nBuild behavior by combining objects, not extending classes.\n\n### 4. Rule of Three\n\nWait until you have three instances before abstracting. Duplication is often better than premature abstraction.\n\n## Quick Start\n\n```python\n# Simple beats clever\n# Instead of a factory\u002Fregistry pattern:\nFORMATTERS = {\"json\": JsonFormatter, \"csv\": CsvFormatter}\n\ndef get_formatter(name: str) -> Formatter:\n    return FORMATTERS[name]()\n```\n\n## Fundamental Patterns\n\n### Pattern 1: KISS - Keep It Simple\n\nBefore adding complexity, ask: does a simpler solution work?\n\n```python\n# Over-engineered: Factory with registration\nclass OutputFormatterFactory:\n    _formatters: dict[str, type[Formatter]] = {}\n\n    @classmethod\n    def register(cls, name: str):\n        def decorator(formatter_cls):\n            cls._formatters[name] = formatter_cls\n            return formatter_cls\n        return decorator\n\n    @classmethod\n    def create(cls, name: str) -> Formatter:\n        return cls._formatters[name]()\n\n@OutputFormatterFactory.register(\"json\")\nclass JsonFormatter(Formatter):\n    ...\n\n# Simple: Just use a dictionary\nFORMATTERS = {\n    \"json\": JsonFormatter,\n    \"csv\": CsvFormatter,\n    \"xml\": XmlFormatter,\n}\n\ndef get_formatter(name: str) -> Formatter:\n    \"\"\"Get formatter by name.\"\"\"\n    if name not in FORMATTERS:\n        raise ValueError(f\"Unknown format: {name}\")\n    return FORMATTERS[name]()\n```\n\nThe factory pattern adds code without adding value here. Save patterns for when they solve real problems.\n\n### Pattern 2: Single Responsibility Principle\n\nEach class or function should have one reason to change.\n\n```python\n# BAD: Handler does everything\nclass UserHandler:\n    async def create_user(self, request: Request) -> Response:\n        # HTTP parsing\n        data = await request.json()\n\n        # Validation\n        if not data.get(\"email\"):\n            return Response({\"error\": \"email required\"}, status=400)\n\n        # Database access\n        user = await db.execute(\n            \"INSERT INTO users (email, name) VALUES ($1, $2) RETURNING *\",\n            data[\"email\"], data[\"name\"]\n        )\n\n        # Response formatting\n        return Response({\"id\": user.id, \"email\": user.email}, status=201)\n\n# GOOD: Separated concerns\nclass UserService:\n    \"\"\"Business logic only.\"\"\"\n\n    def __init__(self, repo: UserRepository) -> None:\n        self._repo = repo\n\n    async def create_user(self, data: CreateUserInput) -> User:\n        # Only business rules here\n        user = User(email=data.email, name=data.name)\n        return await self._repo.save(user)\n\nclass UserHandler:\n    \"\"\"HTTP concerns only.\"\"\"\n\n    def __init__(self, service: UserService) -> None:\n        self._service = service\n\n    async def create_user(self, request: Request) -> Response:\n        data = CreateUserInput(**(await request.json()))\n        user = await self._service.create_user(data)\n        return Response(user.to_dict(), status=201)\n```\n\nNow HTTP changes don't affect business logic, and vice versa.\n\n### Pattern 3: Separation of Concerns\n\nOrganize code into distinct layers with clear responsibilities.\n\n```\n┌─────────────────────────────────────────────────────┐\n│  API Layer (handlers)                                │\n│  - Parse requests                                    │\n│  - Call services                                     │\n│  - Format responses                                  │\n└─────────────────────────────────────────────────────┘\n                        │\n                        ▼\n┌─────────────────────────────────────────────────────┐\n│  Service Layer (business logic)                      │\n│  - Domain rules and validation                       │\n│  - Orchestrate operations                            │\n│  - Pure functions where possible                     │\n└─────────────────────────────────────────────────────┘\n                        │\n                        ▼\n┌─────────────────────────────────────────────────────┐\n│  Repository Layer (data access)                      │\n│  - SQL queries                                       │\n│  - External API calls                                │\n│  - Cache operations                                  │\n└─────────────────────────────────────────────────────┘\n```\n\nEach layer depends only on layers below it:\n\n```python\n# Repository: Data access\nclass UserRepository:\n    async def get_by_id(self, user_id: str) -> User | None:\n        row = await self._db.fetchrow(\n            \"SELECT * FROM users WHERE id = $1\", user_id\n        )\n        return User(**row) if row else None\n\n# Service: Business logic\nclass UserService:\n    def __init__(self, repo: UserRepository) -> None:\n        self._repo = repo\n\n    async def get_user(self, user_id: str) -> User:\n        user = await self._repo.get_by_id(user_id)\n        if user is None:\n            raise UserNotFoundError(user_id)\n        return user\n\n# Handler: HTTP concerns\n@app.get(\"\u002Fusers\u002F{user_id}\")\nasync def get_user(user_id: str) -> UserResponse:\n    user = await user_service.get_user(user_id)\n    return UserResponse.from_user(user)\n```\n\n### Pattern 4: Composition Over Inheritance\n\nBuild behavior by combining objects rather than inheriting.\n\n```python\n# Inheritance: Rigid and hard to test\nclass EmailNotificationService(NotificationService):\n    def __init__(self):\n        super().__init__()\n        self._smtp = SmtpClient()  # Hard to mock\n\n    def notify(self, user: User, message: str) -> None:\n        self._smtp.send(user.email, message)\n\n# Composition: Flexible and testable\nclass NotificationService:\n    \"\"\"Send notifications via multiple channels.\"\"\"\n\n    def __init__(\n        self,\n        email_sender: EmailSender,\n        sms_sender: SmsSender | None = None,\n        push_sender: PushSender | None = None,\n    ) -> None:\n        self._email = email_sender\n        self._sms = sms_sender\n        self._push = push_sender\n\n    async def notify(\n        self,\n        user: User,\n        message: str,\n        channels: set[str] | None = None,\n    ) -> None:\n        channels = channels or {\"email\"}\n\n        if \"email\" in channels:\n            await self._email.send(user.email, message)\n\n        if \"sms\" in channels and self._sms and user.phone:\n            await self._sms.send(user.phone, message)\n\n        if \"push\" in channels and self._push and user.device_token:\n            await self._push.send(user.device_token, message)\n\n# Easy to test with fakes\nservice = NotificationService(\n    email_sender=FakeEmailSender(),\n    sms_sender=FakeSmsSender(),\n)\n```\n\n## Advanced Patterns\n\n### Pattern 5: Rule of Three\n\nWait until you have three instances before abstracting.\n\n```python\n# Two similar functions? Don't abstract yet\ndef process_orders(orders: list[Order]) -> list[Result]:\n    results = []\n    for order in orders:\n        validated = validate_order(order)\n        result = process_validated_order(validated)\n        results.append(result)\n    return results\n\ndef process_returns(returns: list[Return]) -> list[Result]:\n    results = []\n    for ret in returns:\n        validated = validate_return(ret)\n        result = process_validated_return(validated)\n        results.append(result)\n    return results\n\n# These look similar, but wait! Are they actually the same?\n# Different validation, different processing, different errors...\n# Duplication is often better than the wrong abstraction\n\n# Only after a third case, consider if there's a real pattern\n# But even then, sometimes explicit is better than abstract\n```\n\n### Pattern 6: Function Size Guidelines\n\nKeep functions focused. Extract when a function:\n\n- Exceeds 20-50 lines (varies by complexity)\n- Serves multiple distinct purposes\n- Has deeply nested logic (3+ levels)\n\n```python\n# Too long, multiple concerns mixed\ndef process_order(order: Order) -> Result:\n    # 50 lines of validation...\n    # 30 lines of inventory check...\n    # 40 lines of payment processing...\n    # 20 lines of notification...\n    pass\n\n# Better: Composed from focused functions\ndef process_order(order: Order) -> Result:\n    \"\"\"Process a customer order through the complete workflow.\"\"\"\n    validate_order(order)\n    reserve_inventory(order)\n    payment_result = charge_payment(order)\n    send_confirmation(order, payment_result)\n    return Result(success=True, order_id=order.id)\n```\n\n### Pattern 7: Dependency Injection\n\nPass dependencies through constructors for testability.\n\n```python\nfrom typing import Protocol\n\nclass Logger(Protocol):\n    def info(self, msg: str, **kwargs) -> None: ...\n    def error(self, msg: str, **kwargs) -> None: ...\n\nclass Cache(Protocol):\n    async def get(self, key: str) -> str | None: ...\n    async def set(self, key: str, value: str, ttl: int) -> None: ...\n\nclass UserService:\n    \"\"\"Service with injected dependencies.\"\"\"\n\n    def __init__(\n        self,\n        repository: UserRepository,\n        cache: Cache,\n        logger: Logger,\n    ) -> None:\n        self._repo = repository\n        self._cache = cache\n        self._logger = logger\n\n    async def get_user(self, user_id: str) -> User:\n        # Check cache first\n        cached = await self._cache.get(f\"user:{user_id}\")\n        if cached:\n            self._logger.info(\"Cache hit\", user_id=user_id)\n            return User.from_json(cached)\n\n        # Fetch from database\n        user = await self._repo.get_by_id(user_id)\n        if user:\n            await self._cache.set(f\"user:{user_id}\", user.to_json(), ttl=300)\n\n        return user\n\n# Production\nservice = UserService(\n    repository=PostgresUserRepository(db),\n    cache=RedisCache(redis),\n    logger=StructlogLogger(),\n)\n\n# Testing\nservice = UserService(\n    repository=InMemoryUserRepository(),\n    cache=FakeCache(),\n    logger=NullLogger(),\n)\n```\n\n### Pattern 8: Avoiding Common Anti-Patterns\n\n**Don't expose internal types:**\n\n```python\n# BAD: Leaking ORM model to API\n@app.get(\"\u002Fusers\u002F{id}\")\ndef get_user(id: str) -> UserModel:  # SQLAlchemy model\n    return db.query(UserModel).get(id)\n\n# GOOD: Use response schemas\n@app.get(\"\u002Fusers\u002F{id}\")\ndef get_user(id: str) -> UserResponse:\n    user = db.query(UserModel).get(id)\n    return UserResponse.from_orm(user)\n```\n\n**Don't mix I\u002FO with business logic:**\n\n```python\n# BAD: SQL embedded in business logic\ndef calculate_discount(user_id: str) -> float:\n    user = db.query(\"SELECT * FROM users WHERE id = ?\", user_id)\n    orders = db.query(\"SELECT * FROM orders WHERE user_id = ?\", user_id)\n    # Business logic mixed with data access\n\n# GOOD: Repository pattern\ndef calculate_discount(user: User, order_history: list[Order]) -> float:\n    # Pure business logic, easily testable\n    if len(order_history) > 10:\n        return 0.15\n    return 0.0\n```\n\n## Best Practices Summary\n\n1. **Keep it simple** - Choose the simplest solution that works\n2. **Single responsibility** - Each unit has one reason to change\n3. **Separate concerns** - Distinct layers with clear purposes\n4. **Compose, don't inherit** - Combine objects for flexibility\n5. **Rule of three** - Wait before abstracting\n6. **Keep functions small** - 20-50 lines (varies by complexity), one purpose\n7. **Inject dependencies** - Constructor injection for testability\n8. **Delete before abstracting** - Remove dead code, then consider patterns\n9. **Test each layer** - Isolated tests for each concern\n10. **Explicit over clever** - Readable code beats elegant code\n\n## Troubleshooting\n\n**A class is growing and seems to have multiple responsibilities, but splitting it feels wrong.**\nApply the \"reason to change\" test: list every change that could require editing this class. If the list has items from different domains (e.g., HTTP parsing AND business rules AND formatting), split it. If all changes stem from the same domain concern, the class may be appropriately sized.\n\n**Injecting all dependencies through the constructor is producing constructors with 7+ parameters.**\nThis is a sign of too many responsibilities in one class, not a problem with dependency injection. Split the class into smaller units first, then each constructor naturally becomes smaller.\n\n**Composition is producing deeply nested wrapper objects that are hard to trace.**\nKeep the composition shallow (2-3 levels). If wrapping is the only mechanism, consider whether a Protocol-based approach or simple function composition would be cleaner than a chain of decorator objects.\n\n**The rule of three says not to abstract yet, but the duplication is causing bugs when one copy is updated but not the other.**\nDuplication that diverges in dangerous ways should be abstracted sooner. The rule of three is a heuristic, not a law. If the copies are already diverging incorrectly, extract immediately and add a test that exercises the shared behavior.\n\n**A service layer is importing from the API layer, breaking the dependency direction.**\nThis is a layering violation. The service layer must not import from handlers. Introduce a shared types\u002Fmodels layer that both can import from, keeping the dependency arrow pointing downward (API → Service → Repository).\n\n## Related Skills\n\n- [python-testing-patterns](..\u002Fpython-testing-patterns\u002FSKILL.md) — Test each layer in isolation using the dependency injection structure established here\n- [python-project-setup](..\u002Fpython-project-setup\u002FSKILL.md) — Set up project structure and tooling that enforces layer boundaries from the start\n",{"name":5,"description":7},"main","900bb95bbe72cdb94af6f5a620aa5081264b7b6d",".claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fpython-development\u002Fskills\u002Fpython-design-patterns",0,"https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up#readme","https:\u002F\u002Fgithub.com\u002Fsteph-frtech","2026-05-16 00:03:30",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add steph-frtech\u002Fclaude-code-up --skill python-design-patterns",{"tool":37,"command":38},"bunx","bunx skills add steph-frtech\u002Fclaude-code-up --skill python-design-patterns",{"tool":40,"command":41},"pnpm","pnpm dlx skills add steph-frtech\u002Fclaude-code-up --skill python-design-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fpython-development\u002Fskills\u002Fpython-design-patterns\u002FSKILL.md",true,[],[46,53,60,67,74,81],{"skillNo":47,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":50,"categories":51,"keywords":52,"publishedAt":18},"01M72Y1BY6X8TX3DS19Y04NEBQ","example","One-line summary of what this skill does","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002Fskills\u002Fexample\u002FSKILL.md",[],[],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":18},"01M72Y1A38EYR8S9P1MBYDAQTW","writing-plans","Use when you have a spec or requirements for a multi-step task, before touching code","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__writing-plans\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":18},"01M72Y174QSV1B5NV1E4KWHQBR","using-git-worktrees","Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__using-git-worktrees\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M72Y14SQRHHMKG316HGB2CGK","test-driven-development","Use when implementing any feature or bugfix, before writing implementation code","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__test-driven-development\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":18},"01M72Y127BCPRH3BRKPJC3Q3G2","systematic-debugging","Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__systematic-debugging\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":18},"01M72Y1090GJA6B67KPD60WPHH","subagent-driven-development","Use when executing implementation plans with independent tasks in the current session","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__subagent-driven-development\u002FSKILL.md",[],[]]