--- name: python-design-patterns description: Apply KISS, SRP, composition and testable boundaries to a Python-owning task. Use for Python module design, tangled policy/I/O, coupling or abstraction decisions; not TypeScript, React or Next.js implementation merely because general design principles are relevant. --- # 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 Repeated callers are evidence for an abstraction, not a minimum count. A real I/O, lifecycle, safety or compatibility boundary can justify a seam immediately; avoid generalizing merely because snippets look alike. ## 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. **Justify abstractions** - Use real caller, ownership or substitution needs rather than a copy-count rule 6. **Keep functions cohesive** - Extract independent responsibilities, not a mandatory line count 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. **A constructor has many parameters and is difficult to use or test.** Inspect parameter roles, lifetimes and independent reasons to change. Split genuine responsibilities when that improves the caller contract; do not split solely to meet a parameter count or hide dependencies in an unrelated container. **Composition is producing deeply nested wrapper objects that are hard to trace.** Inspect whether wrappers own behavior or merely forward calls. Remove pass-through layers; use a concrete collaborator, function composition or a Protocol when it clarifies the actual seam. Wrapper depth alone is not an acceptance rule. **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