ASD

Python Design Patterns

Principios de diseño en Python como KISS, separación de responsabilidades, responsabilidad única y composición sobre herencia, para diseñar o refactorizar código.

Estrellas
38.8k

en todo el repo

Actividad
47

0–100, la ruta de este skill

Actualizado
hace 2 meses

último commit aquí

Commits
1

últimos 90 días

Contexto
1.2k tok

163 tok en reposo

Paquete
2 archivos

15 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add wshobson/agents --skill python-design-patterns --agent claude-code

Se instala solo en este repositorio.

Qué hace

  • Aplica principios como KISS, SRP, composición sobre herencia y regla de tres al diseño y refactor de código Python
  • Da criterios concretos para decidir si dividir una clase, abstraer código duplicado o usar composición en vez de herencia
  • Incluye ejemplos y una guía de resolución de problemas para casos de acoplamiento excesivo o capas mal separadas

Úsalo cuando

  • Diseñar nuevos componentes o servicios
  • Refactorizar código complejo o enmarañado
  • Decidir si crear una nueva abstracción
  • Elegir entre herencia y composición para una jerarquía de clases

No lo uses cuando

    Qué lo activa

    Di cualquiera de estas frases y el agente debería cargar este skill.

    • Ayúdame a refactorizar esta God class que hace demasiadas cosas
    • ¿Debería usar herencia o composición para este nuevo módulo?
    • Revisa este pull request en busca de acoplamiento excesivo
    • ¿Vale la pena crear una abstracción para este código duplicado?

    SKILL.md

    En inglés

    Python Design Patterns

    Write maintainable Python code using fundamental design principles. These patterns help you build systems that are easy to understand, test, and modify.

    When to Use This Skill

    • Designing new components or services
    • Refactoring complex or tangled code
    • Deciding whether to create an abstraction
    • Choosing between inheritance and composition
    • Evaluating code complexity and coupling
    • Planning modular architectures

    Core Concepts

    1. KISS (Keep It Simple)

    Choose the simplest solution that works. Complexity must be justified by concrete requirements.

    2. Single Responsibility (SRP)

    Each unit should have one reason to change. Separate concerns into focused components.

    3. Composition Over Inheritance

    Build behavior by combining objects, not extending classes.

    4. Rule of Three

    Wait until you have three instances before abstracting. Duplication is often better than premature abstraction.

    Quick Start

    # Simple beats clever
    # Instead of a factory/registry pattern:
    FORMATTERS = {"json": JsonFormatter, "csv": CsvFormatter}
    
    def get_formatter(name: str) -> Formatter:
        return FORMATTERS[name]()
    

    Detailed patterns and worked examples

    Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.

    Best Practices Summary

    1. Keep it simple - Choose the simplest solution that works
    2. Single responsibility - Each unit has one reason to change
    3. Separate concerns - Distinct layers with clear purposes
    4. Compose, don't inherit - Combine objects for flexibility
    5. Rule of three - Wait before abstracting
    6. Keep functions small - 20-50 lines (varies by complexity), one purpose
    7. Inject dependencies - Constructor injection for testability
    8. Delete before abstracting - Remove dead code, then consider patterns
    9. Test each layer - Isolated tests for each concern
    10. Explicit over clever - Readable code beats elegant code

    Troubleshooting

    A class is growing and seems to have multiple responsibilities, but splitting it feels wrong. Apply 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.

    Injecting all dependencies through the constructor is producing constructors with 7+ parameters. This 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.

    Composition is producing deeply nested wrapper objects that are hard to trace. Keep 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.

    The rule of three says not to abstract yet, but the duplication is causing bugs when one copy is updated but not the other. Duplication 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.

    A service layer is importing from the API layer, breaking the dependency direction. This is a layering violation. The service layer must not import from handlers. Introduce a shared types/models layer that both can import from, keeping the dependency arrow pointing downward (API → Service → Repository).

    Related Skills

    • python-testing-patterns — Test each layer in isolation using the dependency injection structure established here
    • python-project-setup — Set up project structure and tooling that enforces layer boundaries from the start

    Reproducido de wshobson/agents bajo licencia MIT. Leer esta página en markdown.

    Archivos

    2 archivos en el paquete. Solo se lee SKILL.md al activarse — las referencias se cargan si el skill decide que las necesita.

    Detalles

    Creador
    wshobson
    Licencia
    MIT
    Recursos incluidos
    referencias
    Repositorio
    wshobson/agents
    Código fuente
    Ver SKILL.md

    Etiquetas

    Más de wshobson/agents

    Este repo incluye 180 skills. Si instalas uno, normalmente ya tienes los demás.

    Úsalo al seleccionar y colocar iconos, imágenes, SVGs, diagramas o infografías de apoyo aprobados en un PPTX editable.

    Costo de contexto al activarse
    344 tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 26 días
    documentos

    Úsalo cuando pidan optimizar un prompt, mejorar su rendimiento, diseñar una plantilla, aplicar chain-of-thought, few-shot prompting o técnicas avanzadas de prompt engineering para producción.

    Costo de contexto al activarse
    1.3k tok
    Tamaño del paquete
    10 archivos
    Última actualización
    el mes pasado
    herramientas desarrollo

    Úsalo al redactar o reparar una especificación JSON con coordenadas explícitas para un PPTX editable.

    Costo de contexto al activarse
    489 tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 26 días
    documentos

    Úsalo para validar o reparar un PPTX editable en cuanto a geometría, accesibilidad, editabilidad nativa, linaje de fuente e integridad del paquete OOXML.

    Costo de contexto al activarse
    409 tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 26 días
    documentos

    Úsalo para analizar un PPTX de referencia en modo solo lectura: estructura, tema, tipografía, ritmo de layout, diagnósticos, catálogos de plantillas derivados o inspección segura del paquete OOXML.

    Costo de contexto al activarse
    689 tok
    Tamaño del paquete
    8 archivos
    Última actualización
    hace 26 días
    documentos

    Úsalo al preparar la narrativa, las fuentes y el contexto de diseño para un nuevo deck PPTX editable.

    Costo de contexto al activarse
    415 tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 26 días
    documentos

    Skills relacionados

    Domina el sistema de tipos avanzado de TypeScript: generics, tipos condicionales, mapped types, template literals y utility types para aplicaciones type-safe.

    Costo de contexto al activarse
    2k tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 2 meses
    herramientas desarrollo

    Patrones de resiliencia en Python: reintentos automáticos, backoff exponencial, timeouts y decoradores tolerantes a fallos para servicios.

    Costo de contexto al activarse
    1.5k tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 2 meses
    herramientas desarrollo

    Organización de proyectos Python, arquitectura de módulos y diseño de APIs públicas con __all__, para nuevos proyectos o reorganización de directorios.

    Costo de contexto al activarse
    1.7k tok
    Tamaño del paquete
    1 archivo
    Última actualización
    hace 6 meses
    herramientas desarrollo