python-patterns について
フレームワーク選定、非同期と同期、型ヒント、プロジェクト構成、テスト、エラー処理を扱う、Python 開発者向けの判断ガイドです。固定のコードパターンをそのまま使うのではなく、要件に応じた選択を重視します。
主な機能
- 01要件に応じたフレームワーク選定
- 02非同期と同期の使い分け
- 03型ヒントと Pydantic による検証
- 04プロジェクト構成と依存性注入の計画
- 05テストとエラー処理の原則
活用シーン
- 01API やフルスタックプロジェクトのフレームワーク選定
- 02I/O 集約タスクでの非同期方式の評価
- 03Python サービスのモジュール構成の計画
- 04重要な処理経路のテストと例外方針の策定
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ vudovn/ ag-kit --skill python-patternsインストール後、Claude Code で/python-patternsを入力して読み込まれたか確認します。
詳細
Python のパターン
Python 開発の原則と意思決定について説明します。 パターンを暗記するのではなく、考え方を身につけましょう。
⚠️ このスキルの使い方
このスキルでは、コピーして使う固定コードではなく、意思決定の原則を学びます。
- 不明な場合は、ユーザーに希望するフレームワークを尋ねます
- コンテキストに基づいて、非同期か同期かを選択します
- 毎回同じフレームワークをデフォルトにしないでください
1. フレームワークの選択
判断ツリー
What are you building?
│
├── API-first / Microservices
│ └── FastAPI (async, modern, fast)
│
├── Full-stack web / CMS / Admin
│ └── Django (batteries-included)
│
├── Simple / Script / Learning
│ └── Flask (minimal, flexible)
│
├── AI/ML API serving
│ └── FastAPI (Pydantic, async, uvicorn)
│
└── Background workers
└── Celery + any framework
比較の原則
| 要素 | FastAPI | Django | Flask |
|---|---|---|---|
| 最適な用途 | API、マイクロサービス | フルスタック、CMS | シンプルな用途、学習 |
| 非同期 | ネイティブ対応 | Django 5.0+ | 拡張機能経由 |
| 管理機能 | 手動で実装 | 組み込み | 拡張機能経由 |
| ORM | 自由に選択 | Django ORM | 自由に選択 |
| 学習曲線 | 低い | 中程度 | 低い |
確認する質問:
- API 専用ですか、それともフルスタックですか?
- 管理インターフェースは必要ですか?
- チームは非同期処理に慣れていますか?
- 既存のインフラストラクチャはありますか?
2. 非同期か同期かの判断
非同期を使う場合
async def is better when:
├── I/O-bound operations (database, HTTP, file)
├── Many concurrent connections
├── Real-time features
├── Microservices communication
└── FastAPI/Starlette/Django ASGI
def (sync) is better when:
├── CPU-bound operations
├── Simple scripts
├── Legacy codebase
├── Team unfamiliar with async
└── Blocking libraries (no async version)
基本原則
I/O-bound → async (waiting for external)
CPU-bound → sync + multiprocessing (computing)
Don't:
├── Mix sync and async carelessly
├── Use sync libraries in async code
└── Force async for CPU work
非同期ライブラリの選択
| 必要な機能 | 非同期ライブラリ |
|---|---|
| HTTP クライアント | httpx |
| PostgreSQL | asyncpg |
| Redis | redis-py (redis.asyncio) |
| ファイル I/O | aiofiles |
| データベース ORM | SQLAlchemy 2.0 async、Tortoise |
3. 型ヒントの方針
型を付ける場合
Always type:
├── Function parameters
├── Return types
├── Class attributes
├── Public APIs
Can skip:
├── Local variables (let inference work)
├── One-off scripts
├── Tests (usually)
よく使う型パターン
# These are patterns, understand them:
# Optional → might be None
from typing import Optional
def find_user(id: int) -> Optional[User]: ...
# Union → one of multiple types
def process(data: str | dict) -> None: ...
# Generic collections
def get_items() -> list[Item]: ...
def get_mapping() -> dict[str, int]: ...
# Callable
from typing import Callable
def apply(fn: Callable[[int], str]) -> str: ...
バリデーションに Pydantic を使う
When to use Pydantic:
├── API request/response models
├── Configuration/settings
├── Data validation
├── Serialization
Benefits:
├── Runtime validation
├── Auto-generated JSON schema
├── Works with FastAPI natively
└── Clear error messages
4. プロジェクト構成の原則
構成の選択
Small project / Script:
├── main.py
├── utils.py
└── requirements.txt
Medium API:
├── app/
│ ├── __init__.py
│ ├── main.py
│ ├── models/
│ ├── routes/
│ ├── services/
│ └── schemas/
├── tests/
└── pyproject.toml
Large application:
├── src/
│ └── myapp/
│ ├── core/
│ ├── api/
│ ├── services/
│ ├── models/
│ └── ...
├── tests/
└── pyproject.toml
FastAPI の構成原則
Organize by feature or layer:
By layer:
├── routes/ (API endpoints)
├── services/ (business logic)
├── models/ (database models)
├── schemas/ (Pydantic models)
└── dependencies/ (shared deps)
By feature:
├── users/
│ ├── routes.py
│ ├── service.py
│ └── schemas.py
└── products/
└── ...
5. Django の原則
Django の非同期処理(Django 5.0+)
Django supports async:
├── Async views
├── Async middleware
├── Async ORM (limited)
└── ASGI deployment
When to use async in Django:
├── External API calls
├── WebSocket (Channels)
├── High-concurrency views
└── Background task triggering
Django のベストプラクティス
Model design:
├── Fat models, thin views
├── Use managers for common queries
├── Abstract base classes for shared fields
Views:
├── Class-based for complex CRUD
├── Function-based for simple endpoints
├── Use viewsets with DRF
Queries:
├── select_related() for FKs
├── prefetch_related() for M2M
├── Avoid N+1 queries
└── Use .only() for specific fields
6. FastAPI の原則
FastAPI での async def と def
Use async def when:
├── Using async database drivers
├── Making async HTTP calls
├── I/O-bound operations
└── Want to handle concurrency
Use def when:
├── Blocking operations
├── Sync database drivers
├── CPU-bound work
└── FastAPI runs in threadpool automatically
依存性注入
Use dependencies for:
├── Database sessions
├── Current user / Auth
├── Configuration
├── Shared resources
Benefits:
├── Testability (mock dependencies)
├── Clean separation
├── Automatic cleanup (yield)
Pydantic v2 との統合
# FastAPI + Pydantic are tightly integrated:
# Request validation
@app.post("/users")
async def create(user: UserCreate) -> UserResponse:
# user is already validated
...
# Response serialization
# Return type becomes response schema
7. バックグラウンドタスク
選択ガイド
| ソリューション | 最適な用途 |
|---|---|
| BackgroundTasks | シンプルなインプロセスのタスク |
| Celery | 分散処理、複雑なワークフロー |
| ARQ | 非同期処理、Redis ベース |
| RQ | シンプルな Redis キュー |
| Dramatiq | アクターベース、Celery よりシンプル |
それぞれを使う場合
FastAPI BackgroundTasks:
├── Quick operations
├── No persistence needed
├── Fire-and-forget
└── Same process
Celery/ARQ:
├── Long-running tasks
├── Need retry logic
├── Distributed workers
├── Persistent queue
└── Complex workflows
8. エラー処理の原則
例外処理の方針
In FastAPI:
├── Create custom exception classes
├── Register exception handlers
├── Return consistent error format
└── Log without exposing internals
Pattern:
├── Raise domain exceptions in services
├── Catch and transform in handlers
└── Client gets clean error response
エラーレスポンスの考え方
Include:
├── Error code (programmatic)
├── Message (human readable)
├── Details (field-level when applicable)
└── NOT stack traces (security)
9. テストの原則
テスト戦略
| 種類 | 目的 | ツール |
|---|---|---|
| ユニット | ビジネスロジック | pytest |
| 統合 | API エンドポイント | pytest + httpx/TestClient |
| E2E | ワークフロー全体 | pytest + DB |
非同期テスト
# Use pytest-asyncio for async tests
import pytest
from httpx import AsyncClient
@pytest.mark.asyncio
async def test_endpoint():
async with AsyncClient(app=app, base_url="http://test") as client:
response = await client.get("/users")
assert response.status_code == 200
フィクスチャの方針
Common fixtures:
├── db_session → Database connection
├── client → Test client
├── authenticated_user → User with token
└── sample_data → Test data setup
10. 判断チェックリスト
実装する前に、次の点を確認してください。
- ユーザーにフレームワークの希望を尋ねましたか?
- このコンテキストに合ったフレームワークを選びましたか?(単にデフォルトを選ぶのではなく)
- 非同期か同期かを決めましたか?
- 型ヒントの方針を立てましたか?
- プロジェクト構成を定義しましたか?
- エラー処理の計画を立てましたか?
- バックグラウンドタスクを検討しましたか?
11. 避けるべきアンチパターン
❌ しないこと:
- シンプルな API に Django をデフォルトで使う(FastAPI のほうが適している場合があります)
- 非同期コードで同期ライブラリを使う
- 公開 API に型ヒントを付けない
- ビジネスロジックをルートやビューに記述する
- N+1 クエリを無視する
- 非同期と同期を不用意に混在させる
✅ すること:
- コンテキストに基づいてフレームワークを選ぶ
- 非同期処理の要件を確認する
- バリデーションに Pydantic を使う
- 関心事を分離する(ルート → サービス → リポジトリ)
- 重要な処理経路をテストする
覚えておきましょう:Python のパターンとは、あなたの具体的なコンテキストに応じた意思決定です。コードをコピーするのではなく、アプリケーションに最適な方法を考えましょう。
コメント
Markdown 対応