mcpField
P
python-patterns

python-patterns

github.com/davila7開発33.1k359 回インストール1 日前に更新
リポジトリ

python-patterns について

python-patternsは、状況に応じたPython開発の判断を支援するスキルです。特定のテンプレートを押し付けず、フレームワークや非同期処理、構成などを扱います。

主な機能

  1. 01フレームワーク選択の指針
  2. 02非同期・同期の判断
  3. 03型ヒントとPydantic
  4. 04プロジェクト構成の原則
  5. 05テストとエラー処理

活用シーン

  1. 01新しいAPIのフレームワーク選定
  2. 02I/O処理方式の判断
  3. 03Pythonプロジェクト構成の計画

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/davila7/claude-code-templates --skill python-patterns

インストール後、Claude Code で/python-patternsを入力して読み込まれたか確認します。

詳細

Python パターン

2025年向けの Python 開発の原則と意思決定。 パターンを暗記するのではなく、考えることを学びましょう。


⚠️ このスキルの使い方

このスキルは、そのままコピーする固定のコードではなく、意思決定の原則を教えるものです。

  • 方針が不明確な場合は、フレームワークの希望をユーザーに確認してください
  • async と sync の選択は、その時の文脈に基づいて行ってください
  • 毎回同じフレームワークをデフォルトで選ばないでください

1. フレームワークの選択(2025年)

決定木
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
比較の原則
要素FastAPIDjangoFlask
最適な用途API、マイクロサービスフルスタック、CMSシンプル、学習用
Asyncネイティブ対応Django 5.0+拡張機能経由
管理画面手動組み込み拡張機能経由
ORM任意に選択Django ORM任意に選択
学習曲線低い中程度低い
確認すべき選択の質問:
  1. API のみですか、それともフルスタックですか?
  2. 管理画面は必要ですか?
  3. チームは async に慣れていますか?
  4. 既存のインフラはありますか?

2. Async と Sync の判断

Async を使うべき場合
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
Async ライブラリの選択
必要な機能Async ライブラリ
HTTP クライアントhttpx
PostgreSQLasyncpg
Redisaioredis / redis-py async
ファイル I/Oaiofiles
データベース ORMSQLAlchemy 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 の原則(2025年)

Django の Async(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分散処理、複雑なワークフロー
ARQAsync、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. テストの原則

テスト戦略
種類目的ツール
Unitビジネスロジックpytest
IntegrationAPI エンドポイントpytest + httpx/TestClient
E2Eワークフロー全体pytest + DB
Async のテスト
# 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. 意思決定チェックリスト

実装前に確認してください:

  • フレームワークの希望についてユーザーに確認したか?
  • この文脈に合ったフレームワークを選んだか?(単にデフォルトではなく)
  • Async と Sync のどちらにするか決めたか?
  • 型ヒントの方針を計画したか?
  • プロジェクト構造を定義したか?
  • エラー処理を計画したか?
  • バックグラウンドタスクを検討したか?

11. 避けるべきアンチパターン

❌ やってはいけないこと:
  • シンプルな API に Django をデフォルトで使う(FastAPI の方が適している場合があります)
  • Async のコードで sync ライブラリを使う
  • 公開 API で型ヒントを省略する
  • ビジネスロジックをルート/ビューに書く
  • N+1 クエリを無視する
  • async と sync を無計画に混在させる
✅ すべきこと:
  • 文脈に基づいてフレームワークを選ぶ
  • Async の要件について確認する
  • バリデーションには Pydantic を使う
  • 関心事を分離する(ルート → サービス → リポジトリ)
  • 重要な経路をテストする

覚えておいてください: Python パターンは、あなた自身の 特定の文脈に対する意思決定についてのものです。コードをコピーするのではなく、何があなたのアプリケーションに最も役立つかを考えてください。

コメント