К основному содержанию
плагин

python-clean-architecture — плагин для Claude Code: как установить

Плагин python-clean-architecture внедряет принципы чистой архитектуры в проекты на Python и FastAPI. Он проверяет слои приложения, находит сильную связанность и генерирует каркасы сервисов.

MIT ★ 11 обновлён 2026-06-19

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add anthropics/claude-plugins-community
/plugin install python-clean-architecture@claude-community
Открыть на GitHub

Что делает python-clean-architecture

Инструмент выстраивает архитектуру проектов на Python и FastAPI. Он проверяет разделение на слои и следит за изоляцией роутеров от базы данных. Вместо тяжёлого наследования плагин предлагает интерфейсы Protocol и вызовы Callable. Для ревизии кода предусмотрена команда /review-architecture, которая находит нарушения границ слоёв и сильное зацепление компонентов.

Для ускорения работы плагин разворачивает проект через /scaffold-api и добавляет сущности вызовом /add-endpoint. Обучающий режим /learn-architecture объясняет паттерны на примере готового API и сопоставляет их с вашим кодом. При этом режим обучения только анализирует проект и не изменяет файлы.

Команда /scaffold-tests генерирует тесты строго с заглушками DataInterfaceStub. Поэтому проверку с реальной базой данных инструмент не создаёт.

Какие задачи решает

  • развернуть каркас проекта FastAPI с чистой слоистой архитектурой
  • найти нарушения границ между роутерами, операциями и базой данных
  • разбить разросшийся класс на независимые компоненты через /extract-god-class
  • сгенерировать изолированные тесты операций с заглушками DataInterfaceStub
  • заменить тяжёлые иерархии классов на протоколы и функциональные вызовы

Примеры запросов агенту

  • Разверни новый проект FastAPI с чистой архитектурой
  • /review-architecture src/
  • /add-endpoint booking

Как установить python-clean-architecture

Через маркетплейс плагинов

/plugin marketplace add anthropics/claude-plugins-community
/plugin install python-clean-architecture@claude-community

По шагам, с командами для каждой платформы: Плагины Claude Code: маркетплейсы, установка и как собрать свой

Вопросы о python-clean-architecture

Как установить python-clean-architecture в Claude Code?

Выполните в консоли команду /plugin marketplace add anthropics/claude-plugins-community. Затем установите плагин вызовом /plugin install python-clean-architecture@claude-community.

Что делает python-clean-architecture?

Плагин автоматизирует проектирование и ревизию проектов на Python и FastAPI по канонам чистой архитектуры. Он инспектирует разделение логики по слоям и помогает собирать сервисы с внедрением зависимостей через протоколы.

Требуется ли база данных для запуска тестов из scaffold-tests?

Нет, команда /scaffold-tests генерирует тесты для операций на основе заглушек DataInterfaceStub. Логика проверяется изолированно в памяти без поднятия базы данных.

Исходный текст

SKILL.md · MIT
# python-clean-architecture — Claude Code Plugin

A [Claude Code](https://docs.anthropic.com/en/docs/claude-code) plugin that provides Clean Architecture guidance for Python/FastAPI projects. Scaffold, review, and refactor Python projects with design principles and Pythonic patterns — directly inside Claude Code.

## Attribution

The principles, patterns, and architectural approach in this plugin are inspired by and synthesized from [Arjan Codes](https://www.arjancodes.com/)' courses:

- **The Software Designer Mindset** — Seven core design principles (cohesion, coupling, abstractions, composition, creation/use separation, data-first design, simplicity)
- **Pythonic Patterns** — Classic GoF patterns reimagined for Python using Protocol, Callable, functools.partial, and closures
- **Complete Extension** — Three-layer FastAPI architecture (Routers → Operations → Database) with Protocol-based dependency injection

The specific Pythonic framing (Protocol-based DI, functional pattern progression, three-layer FastAPI architecture) originates from his teaching. This plugin distills those principles into actionable guidance for Claude Code — it is not a reproduction of course content. If you find this useful, consider supporting Arjan's work at [arjancodes.com](https://www.arjancodes.com/), [github.com/arjancodes](https://github.com/arjancodes), and [youtube.com/arjancodes](https://www.youtube.com/arjancodes).

## Installation

1. Add the marketplace:
```
/plugin marketplace add MKToronto/python-clean-architecture
```

2. Install the plugin:
```
/plugin install python-clean-architecture@python-clean-architecture
```

3. Restart Claude Code (`/exit` then `claude`) to load the plugin.

Or download the repo and test locally without installing:

```bash
git clone https://github.com/MKToronto/python-clean-architecture.git
claude --plugin-dir /path/to/python-clean-architecture
```

## Updating

```
/plugin marketplace update python-clean-architecture
```

Then restart Claude Code (`/exit` then `claude`).

## Usage

### Automatic (Skill)

The skill triggers automatically when you ask Claude Code to:

- "Scaffold a new FastAPI project"
- "Set up clean architecture"
- "Refactor to clean architecture"
- "Add a new endpoint / router / use case / repository"
- "Review my code structure"
- "Apply design patterns in Python"
- "Decouple my code"
- "Make my code testable"

Or mention: layered architecture, dependency injection, Protocol-based design, Pythonic design patterns.

### Slash Commands

```
/review-architecture              Review current directory
/review-architecture src/         Review a specific directory
/review-architecture app/main.py  Review a specific file
```

The review checks:
- **Architecture layers** — Three-layer separation, no layer skipping, router as composition root
- **7 design principles** — Cohesion, coupling, abstractions, composition, creation/use, data-first, simplicity
- **22 code quality rules** — Naming, nesting, types, error handling, imports, structure
- **Pythonic patterns** — All 25 patterns checked (Strategy as Callable, Factory as dict mapping, Protocol over ABC, etc.)

Findings are reported by severity (Critical / Important / Suggestions) with file/line references and fix snippets.

### All Commands

**Review & Analysis:**
```
/review-architecture [path]       Full architecture review (standard or in-depth)
/review-api-design [path]         Review REST API endpoints for HTTP conventions
/check-quality [path]             Quick check against 22 code quality rules
/suggest-patterns [path]          Recommend Pythonic design patterns for your code
/decouple [path]                  Find tight coupling and suggest DI improvements
```

**Refactoring:**
```
/make-pythonic [path]             Refactor to Pythonic patterns (ABC→Protocol, if/elif→dict, etc.)
/extract-god-class [path]         Find and split god classes into focused collaborators
```

**Learning:**
```
/learn-architecture [topic]       Learn a design or architecture topic — theory + the Pythonic way + your code
```

`/learn-architecture` explains rather than edits. Pick any topic from the skill (the 7 principles, three-layer architecture, the 25 Pythonic patterns, GRASP, DDD, code smells, REST, Python craft) and get either a **Lesson** (structured walkthrough) or a **Drill** (interactive Socratic Q&A). Every topic is grounded twice: a canonical illustration from the bundled hotel-API example, plus an analysis of *your* code — whether the concept already applies, could apply, or should apply (a violation to fix). Each lesson ends with trade-offs, the "commonly confused with" comparison (Strategy vs State, Adapter vs Facade…), and self-check questions.

**Scaffolding & Testing:**
```
/scaffold-api <project-name>      Generate a new FastAPI project with clean architecture
/add-endpoint <entity-name>       Scaffold a new endpoint across all three layers
/scaffold-tests [path]            Generate stub-based tests for existing operations
```

`/scaffold-api` generates a full project structure with Pydantic models, operations, routers, database layer, and tests. `/add-endpoint` adds a new entity to an existing project — it creates files across all three layers (router + operations + DB model + Pydantic models + tests) and wires them into `main.py`. `/scaffold-tests` generates DataInterfaceStub-based tests for existing operations without requiring a database.

## What's Inside

```text
python-clean-architecture/
├── .claude-plugin/
│   ├── plugin.json
│   └── marketplace.json
├── README.md
├── LICENSE
├── commands/
│   ├── review-architecture.md
│   ├── review-api-design.md
│   ├── check-quality.md
│   ├── suggest-patterns.md
│   ├── decouple.md
│   ├── make-pythonic.md
│   ├── extract-god-class.md
│   ├── learn-architecture.md
│   ├── scaffold-api.md
│   ├── scaffold-tests.md
│   └── add-endpoint.md
└── skills/clean-architecture/
    ├── SKILL.md
    ├── references/
    │   ├── design-principles.md
    │   ├── layered-architecture.md
    │   ├── testable-api.md
    │   ├── testing-advanced.md
    │   ├── rest-api-design.md
    │   ├── code-quality.md
    │   ├── classes-and-dataclasses.md
    │   ├── function-design.md
    │   ├── data-structures.md
    │   ├── error-handling.md
    │   ├── monadic-error-handling.md
    │   ├── types-and-type-hints.md
    │   ├── project-organization.md
    │   ├── context-managers.md
    │   ├── decorators.md
    │   ├── async-patterns.md
    │   ├── pydantic-validation.md
    │   ├── pattern-matching.md
    │   ├── grasp-principles.md
    │   ├── domain-driven-design.md
    │   ├── pythonic-patterns.md
    │   └── patterns/          (25 pattern files)
    │       ├── strategy.md
    │       ├── registry.md
    │       ├── command.md
    │       ├── builder.md
    │       ├── repository.md
    │       ├── cqrs.md
    │       └── ...
    └── examples/
        └── fastapi-hotel-api/
            ├── main.py
            ├── models/
            ├── operations/
            ├── routers/
            └── db/
```

## Key Concepts

### Three-Layer Architecture

```
Routers (API)  →  Operations (business logic)  →  Database (persistence)
```

Each layer depends only on the layer below. The router is the composition root where concrete DB implementations are injected into operations via the `DataInterface` Protocol.

### Seven Design Principles

1. High Cohesion — Single responsibility per unit
2. Low Coupling — Minimize dependencies, Law of Demeter
3. Depend on Abstractions — Protocol + Callable for DI
4. Composition over Inheritance — Never mixins, shallow hierarchies only
5. Separate Creation from Use — Dict mapping, creator functions, one composition root
6. Start with the Data — Information Expert, fix data structures first
7. Keep Things Simple — DRY, KISS, YAGNI (but avoid hasty abstractions)

### Pythonic Pattern Defaults

- Protocol over ABC (unless shared superclass state needed)
- `functools.partial` over wrapper classes
- Closures over factory class hierarchies
- `Callable` type aliases over single-method abstract classes
- Dict mapping over if/elif chains
- Readability over dogmatic functional purity

25 design patterns implemented the Pythonic way:

**Core Patterns:**
- **Strategy** — `Callable` type alias, pass functions as args
- **Abstract Factory** — Tuples of functions + `functools.partial`
- **Bridge** — `Callable` type alias replaces abstract reference
- **Command** — Functions returning undo closures
- **Pub/Sub** — Dict-based `subscribe(event, handler)` / `post_event(event, data)`
- **Registry** — `dict[str, Callable]` mapping + `**kwargs` unpacking
- **Template Method** — Free function + Protocol parameter
- **Pipeline** — `functools.reduce` for composition
- **Callback / Wrapper / Builder** — Functional patterns for event handling, interface translation, and configuration

**Extended Patterns:**
- **Value Objects** — Subclass built-in types with `__new__` validation, or frozen dataclass
- **Event Sourcing** — Immutable events, append-only EventStore, projection functions
- **CQRS** — Separate write model + read projection, projector function after writes
- **Builder** — Fluent API with `Self` return type, `.build()` returns frozen product
- **Unit of Work** — Context manager wrapping transaction: commit on success, rollback on error
- **Singleton** — Module-level instance (preferred), or metaclass with `_instances` dict
- **State** — Protocol-based state objects, context delegates to current state
- **Adapter** — Protocol interface + `functools.partial` for single-method adaptation
- **Facade** — Simplified interface class, `functools.partial` to bind dependencies
- **Retry** — `@retry` decorator with exponential backoff, fallback strategies
- **Lazy Loading** — `functools.cache`, `cached_property`, generators, `__getattr__`
- **Repository** — Protocol interface for CRUD, concrete implementations per storage backend
- **Fluent Interface** — Methods return `self` for chaining, domain-specific verbs for readability
- **Plugin Architecture** — Config-driven creation, `importlib` auto-discovery, self-registering modules

## Example Output

See the [full example review](https://mktoronto.github.io/python-clean-architecture/#example) — a color-coded `/review-architecture` run against a test bookstore-api project (15 findings with before/after code).

## Also available for

- **Codex CLI** — [python-clean-architecture-codex](https://github.com/MKToronto/python-clean-architecture-codex) (agent skill for Codex)

© MKToronto · MIT · MKToronto/python-clean-architecture

Похожие плагины

Все плагины по теме «Бэкенд и API» →
clean-architecture Giuseppe Trisciuoglio Скилл clean-architecture для Claude Code задаёт шаблоны слоистой архитектуры Python-бэкенда на FastAPI или Flask: домен, сценарии, порты и адаптеры, репозитории. Разделяет код по слоям. CX Codex +1 ★ 372звёзд репо architecture-patterns OrchestKit Скилл architecture-patterns проверяет соблюдение чистой архитектуры, деление бэкенда на слои и глубину вложенности папок. Включается при проектировании границ сервисов и рефакторинге. CX Codex +1 236установок Python Backend Architecture Review rknall Скилл Python Backend Architecture Review для Claude Code: ревью архитектуры Python-бэкенда по системе, масштабируемости, безопасности и API. Разбирает документ проекта, находит узкие места в дизайне до релиза. CX Codex +1 528установок python-refactor-expert Giuseppe Trisciuoglio Субагент python-refactor-expert для Claude Code переписывает Python-код без изменения логики: наводит порядок в архитектуре, выносит настройки и внедряет тайпхинты. Пригодится после реализации новых фич. CX Codex ★ 372звёзд репо go-backend-clean-architecture rebyteai-template Скилл go-backend-clean-architecture разворачивает в проекте шаблон Go-бэкенда на Gin с MongoDB, JWT-авторизацией и слоями Clean Architecture — от клонирования до запуска. CX Codex +1 105установок python-testing-strategies c0x12c Скилл python-testing-strategies задаёт агенту правила написания тестов для FastAPI: pytest-asyncio, httpx AsyncClient, фабрики данных и обязательные проверки на каждый эндпоинт. CX Codex +1 ★ 111звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой