# Python Design Patterns > Patrones de diseño en Python: KISS, separación de responsabilidades, responsabilidad única y composición sobre herencia, para diseñar, refactorizar y revisar código. Fuente: https://skillsagentes.com/skills/wshobson/agents/python-design-patterns Markdown: https://skillsagentes.com/skills/wshobson/agents/python-design-patterns.md Repositorio: https://github.com/wshobson/agents Autor: wshobson Licencia: MIT Actualizado: el mes pasado Coste de contexto: 163 tok instalada, 1.2k tok al activarse, 3.9k tok con todos los archivos del bundle Bundle: 2 archivos, 15 KB Permisos que pide: ninguno declarado ## Instalación Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina. ```bash # Claude Code npx -y skills add wshobson/agents --skill python-design-patterns --agent claude-code # Cursor npx -y skills add wshobson/agents --skill python-design-patterns --agent cursor # Codex npx -y skills add wshobson/agents --skill python-design-patterns --agent codex # Gemini CLI npx -y skills add wshobson/agents --skill python-design-patterns --agent gemini # Windsurf npx -y skills add wshobson/agents --skill python-design-patterns --agent windsurf # Cline npx -y skills add wshobson/agents --skill python-design-patterns --agent cline ``` ## Qué hace - Aplica principios de diseño (KISS, SRP, composición sobre herencia, regla de tres) al escribir o revisar código Python - Guía la refactorización de clases o funciones que han crecido demasiado o mezclan responsabilidades - Ayuda a decidir si crear una nueva abstracción o tolerar la duplicación - Evalúa pull requests en busca de acoplamiento excesivo o fuga de tipos internos ## Cuándo usarla - Al diseñar nuevos componentes o servicios desde cero - Al refactorizar una God class o función monolítica demasiado grande - Al decidir si añadir una nueva abstracción o vivir con duplicación - Al elegir entre herencia y composición para una nueva jerarquía de clases ## Qué la activa - "Ayúdame a refactorizar esta clase que hace demasiadas cosas" - "¿Debería usar herencia o composición para este nuevo diseño?" - "Revisa este pull request y dime si hay acoplamiento excesivo" - "¿Ya es momento de abstraer este código duplicado?" ## Archivos - SKILL.md — 5 KB - references/details.md — 11 KB ## SKILL.md Reproducido tal cual desde wshobson/agents bajo MIT. Esta sección es el documento original y está 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 ```python # 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](../python-testing-patterns/SKILL.md) — Test each layer in isolation using the dependency injection structure established here - [python-project-structure](../python-project-structure/SKILL.md) — Organize modules and directory layout so layer boundaries are explicit from the start ## Dónde encaja - Categoría: [Herramientas para desarrolladores](https://skillsagentes.com/categorias/herramientas-desarrollo.md) — Skills que cambian cómo tu agente escribe, revisa y despliega código. - Creador: [wshobson](https://skillsagentes.com/creators/wshobson.md) — 183 skills en el directorio - [Todas las skills](https://skillsagentes.com/skills.md) - [Ranking de instalaciones](https://skillsagentes.com/ranking.md) ## Otras skills del mismo repositorio - [Hermes Tweet](https://skillsagentes.com/skills/wshobson/agents/hermes-tweet.md): Instala y opera Hermes Tweet, un plugin de Hermes Agent para investigar X/Twitter, leer timelines, analizar tweets y ejecutar operaciones privadas o de cambio de estado con aprobación previa. - [Superself](https://skillsagentes.com/skills/wshobson/agents/superself.md): Úsalo cuando un proyecto guarda su estado en Superself: lee `self context` al iniciar sesión, vincula el trabajo a una work unit, reporta con evidencia y registra decisiones confirmadas. - [Grounded Vault](https://skillsagentes.com/skills/wshobson/agents/grounded-vault.md): Úsalo para mantener un almacén Markdown de conocimiento donde cada afirmación compilada se rastrea hasta una fuente inmutable y el drift se detecta con git diff sin gastar tokens. - [Postgresql Table Design](https://skillsagentes.com/skills/wshobson/agents/postgresql-table-design.md): Úsalo al diseñar o revisar un esquema específico de PostgreSQL: buenas prácticas, tipos de datos, indexación, restricciones, patrones de rendimiento y funciones avanzadas. - [Prompt Engineering Patterns](https://skillsagentes.com/skills/wshobson/agents/prompt-engineering-patterns.md): Ú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. --- Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)