Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .claude/commands/new-pattern.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
description: Scaffold a new pattern unit under patterns/<group>/<slug>
argument-hint: <group>/<slug> "Pattern Name"
---

Scaffold a new pattern unit for $ARGUMENTS.

1. Validate the group is one of: principle, python, creational, structural, behavioral, modern.
Refuse anything else.
2. Create `patterns/<group>/<slug>/` with the exact template from CLAUDE.md:
README.md (frontmatter with `id: <group>/<slug>`, all schema keys present,
`verdict:` left as `use-with-care` with a `TODO` caveat), empty-but-importable
`__init__.py`, and stub `naive.py`, `pythonic.py`, `real_world.py` each with a
typed `main() -> None` and script guard, plus `tests/test_<slug>.py` with one
failing `test_todo` marked `xfail(reason="unit not yet written")`.
3. Run `make check` and report the result. Do not write the actual pattern content —
scaffolding only.
14 changes: 14 additions & 0 deletions .claude/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"permissions": {
"allow": [
"Bash(make check)",
"Bash(make lint)",
"Bash(make test)",
"Bash(make typecheck)",
"Bash(uv run pytest:*)",
"Bash(uv run ruff:*)",
"Bash(uv run mypy:*)",
"Bash(uv sync:*)"
]
}
}
49 changes: 49 additions & 0 deletions .claude/skills/pattern-authoring/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
name: pattern-authoring
description: How to write a complete pattern unit for this repo — variant roles, frontmatter, verdict rubric, and test expectations. Use when authoring or reviewing any patterns/<group>/<slug>/ content.
---

# Authoring a pattern unit

## The three variants have distinct jobs — don't blur them

- **naive.py** — the Gang-of-Four/Java translation, faithfully. Class-heavy,
interface-driven, even when it looks silly in Python. It exists so a reader can
diff it against pythonic.py and *see* what Python absorbs. Keep it correct and
typed, but do not "improve" it.
- **pythonic.py** — what a fluent Python developer writes for the same problem.
If the pattern collapses into a language feature (first-class functions, modules,
dunder protocols, decorators, singledispatch), show the collapse and name it.
- **real_world.py** — a small program using the *stdlib's own* embodiment of the
pattern (e.g. Iterator → generators/`iter()`, Decorator → `functools.wraps`,
Prototype → `copy.deepcopy`, Command → `functools.partial` callbacks). Import the
stdlib machinery; don't reimplement it.

## Choosing the verdict

- `pythonic` — the pattern, in its pythonic form, is what you'd genuinely recommend.
- `use-with-care` — legitimate uses exist, but each caveat in the frontmatter must
name a concrete failure mode (not "be careful").
- `prefer-alternative` — the honest answer is "don't"; `pythonic.py` must then show
the alternative, and `caveats` must name it explicitly (e.g. "You almost always
want the Global Object pattern instead").

When python-patterns.guide has a chapter, its verdict wins; link it in `guide_url`
and align the prose with its argument. Where it has none, reason from its principles
(composition over inheritance, callables over class hierarchies).

## Prose in README.md (after the frontmatter)

Sections, in order: **Problem** (2–4 sentences, concrete), **Naive solution** (what
the GoF book prescribes and why it looks that way), **Pythonic solution** (the
collapse or refinement, with the language feature named), **In the wild** (where the
stdlib/ecosystem does this), **Verdict** (one honest paragraph). ~1 page total.
No history lessons, no UML.

## Tests

- One test file per unit, covering all three variants.
- Assert observable behavior: outputs, state transitions, raised exceptions,
identity where the pattern is *about* identity (singleton, flyweight).
- Async units use pytest-asyncio; everything else stays synchronous.
- Never test print output by capsys unless the demo output IS the behavior.
29 changes: 29 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: ci

on:
push:
branches: [main, staging]
pull_request:

jobs:
check:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.11", "3.12", "3.13"]
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install
run: uv sync --group dev
- name: Lint
run: |
uv run ruff check .
uv run ruff format --check .
- name: Typecheck
run: uv run mypy
- name: Test
run: uv run pytest
24 changes: 23 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,23 @@
__pycache__
# Python
__pycache__/
*.py[cod]
*.egg-info/
dist/
build/
.venv/

# Tooling caches
.pytest_cache/
.mypy_cache/
.ruff_cache/
.coverage
htmlcov/
uv.lock

# Editors / OS
.idea/
.vscode/
.DS_Store

# oh-my-claudecode runtime state
.omc/
67 changes: 67 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Agent instructions — python-design-patterns

Companion catalog to [python-patterns.guide](https://python-patterns.guide/): every design
pattern as runnable, tested, typed Python — plus an MCP server (`src/design_patterns_mcp/`)
that serves the catalog to agents.

## Layout

- `patterns/<group>/<slug>/` — one directory per pattern ("unit"). Groups:
`principle`, `python`, `creational`, `structural`, `behavioral`, `modern`.
- `src/design_patterns/` — catalog loader (frontmatter → typed `Pattern` objects).
- `src/design_patterns_mcp/` — FastMCP server (tools, resources, prompts, sandbox).
- Legacy flat dirs (`behavioral/`, `combos/`, `creational/`, `structural/`) are
pre-migration code: excluded from lint, deleted as units absorb them. Do not add to them.

## Pattern unit template

Every unit has exactly this shape (scaffold one with `/new-pattern`):

```
patterns/<group>/<slug>/
├── README.md # YAML frontmatter + prose
├── __init__.py
├── naive.py # the literal 1994/Java-style translation
├── pythonic.py # what you actually write in Python
├── real_world.py # the pattern as it appears in the stdlib
└── tests/test_<slug>.py
```

- Each `.py` variant is import-safe (no side effects at import) and has a
`main() -> None` demo runnable as a script (`if __name__ == "__main__": main()`).
- Tests import the variants and assert behavior — never just "it runs".
- Full type hints; `mypy --strict` must pass.

## Frontmatter schema (the MCP server indexes this — keep it valid)

```yaml
id: structural/decorator # must equal <group>/<slug>
name: Decorator
aliases: [wrapper] # alternate names searchers might use
guide_url: https://python-patterns.guide/gang-of-four/decorator-pattern/ # or null
problem: "One sentence: the problem this pattern solves."
symptoms: ["logging every call", "caching results"] # phrases a user might say
verdict: pythonic # pythonic | use-with-care | prefer-alternative
caveats: ["Always use functools.wraps."]
stdlib_sightings: [functools.wraps, contextlib.contextmanager]
```

Verdicts: `pythonic` = use it as shown; `use-with-care` = valid but has sharp edges
(caveats say which); `prefer-alternative` = the naive form exists for study, the
pythonic file shows what to write instead (e.g. Singleton → module global,
Visitor → singledispatch). See `docs/verdicts.md`.

## Workflow

- Branches: `main ← staging ← feat/<slug>`. PRs target `staging`. Never push to `main`.
- Gate before any PR: `make check` (ruff lint+format, mypy --strict, pytest+cov) green.
- Commit style: `<type>: <summary>` (`feat`, `fix`, `chore`, `docs`, `refactor`).
- Toolchain is uv only — no pip/poetry. `make install` to set up.

## Writing style for pattern prose

- Lead with the problem, not the pattern name's history.
- Say plainly when Python makes the pattern unnecessary — that honesty is the
point of the repo. Cite the guide chapter when one exists.
- naive.py mirrors the GoF book faithfully, even when un-Pythonic (that's its job);
pythonic.py is idiomatic; real_world.py points at real stdlib usage.
67 changes: 67 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# python-design-patterns

Companion catalog to [python-patterns.guide](https://python-patterns.guide/): every design
pattern as runnable, tested, typed Python — plus an MCP server (`src/design_patterns_mcp/`)
that serves the catalog to agents.

## Layout

- `patterns/<group>/<slug>/` — one directory per pattern ("unit"). Groups:
`principle`, `python`, `creational`, `structural`, `behavioral`, `modern`.
- `src/design_patterns/` — catalog loader (frontmatter → typed `Pattern` objects).
- `src/design_patterns_mcp/` — FastMCP server (tools, resources, prompts, sandbox).
- Legacy flat dirs (`behavioral/`, `combos/`, `creational/`, `structural/`) are
pre-migration code: excluded from lint, deleted as units absorb them. Do not add to them.

## Pattern unit template

Every unit has exactly this shape (scaffold one with `/new-pattern`):

```
patterns/<group>/<slug>/
├── README.md # YAML frontmatter + prose
├── __init__.py
├── naive.py # the literal 1994/Java-style translation
├── pythonic.py # what you actually write in Python
├── real_world.py # the pattern as it appears in the stdlib
└── tests/test_<slug>.py
```

- Each `.py` variant is import-safe (no side effects at import) and has a
`main() -> None` demo runnable as a script (`if __name__ == "__main__": main()`).
- Tests import the variants and assert behavior — never just "it runs".
- Full type hints; `mypy --strict` must pass.

## Frontmatter schema (the MCP server indexes this — keep it valid)

```yaml
id: structural/decorator # must equal <group>/<slug>
name: Decorator
aliases: [wrapper] # alternate names searchers might use
guide_url: https://python-patterns.guide/gang-of-four/decorator-pattern/ # or null
problem: "One sentence: the problem this pattern solves."
symptoms: ["logging every call", "caching results"] # phrases a user might say
verdict: pythonic # pythonic | use-with-care | prefer-alternative
caveats: ["Always use functools.wraps."]
stdlib_sightings: [functools.wraps, contextlib.contextmanager]
```

Verdicts: `pythonic` = use it as shown; `use-with-care` = valid but has sharp edges
(caveats say which); `prefer-alternative` = the naive form exists for study, the
pythonic file shows what to write instead (e.g. Singleton → module global,
Visitor → singledispatch). See `docs/verdicts.md`.

## Workflow

- Branches: `main ← staging ← feat/<slug>`. PRs target `staging`. Never push to `main`.
- Gate before any PR: `make check` (ruff lint+format, mypy --strict, pytest+cov) green.
- Commit style: `<type>: <summary>` (`feat`, `fix`, `chore`, `docs`, `refactor`).
- Toolchain is uv only — no pip/poetry. `make install` to set up.

## Writing style for pattern prose

- Lead with the problem, not the pattern name's history.
- Say plainly when Python makes the pattern unnecessary — that honesty is the
point of the repo. Cite the guide chapter when one exists.
- naive.py mirrors the GoF book faithfully, even when un-Pythonic (that's its job);
pythonic.py is idiomatic; real_world.py points at real stdlib usage.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019-2026 SuperElectron

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
23 changes: 23 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
.PHONY: install lint format typecheck test check clean

install: ## Sync dev environment
uv sync --group dev

lint: ## Ruff lint + format check
uv run ruff check .
uv run ruff format --check .

format: ## Auto-fix lint and formatting
uv run ruff check --fix .
uv run ruff format .

typecheck: ## mypy --strict
uv run mypy

test: ## Run test suite with coverage
uv run pytest

check: lint typecheck test ## Everything CI runs

clean:
rm -rf .pytest_cache .mypy_cache .ruff_cache .coverage htmlcov dist build
Loading
Loading