mcpField
P
python-patterns

python-patterns

github.com/sickn33開発48.7k1.3k 回インストール今日更新
リポジトリ

python-patterns について

Python 開発者がアーキテクチャ、フレームワーク、非同期処理、プロジェクト構成を検討するためのスキルです。定型解の転用ではなく、状況に応じた選択を重視します。

主な機能

  1. 01要件に応じたフレームワーク選定
  2. 02非同期と同期の判断
  3. 03型ヒントと検証の指針
  4. 04プロジェクト構成の原則
  5. 05テストとエラー処理

活用シーン

  1. 01API 用フレームワークの選定
  2. 02非同期 I/O パターンの計画
  3. 03Python アプリの構成
  4. 04バックグラウンドタスク方式の選定

インストール

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

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill python-patterns

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

詳細

翻訳後に原文が更新されています。最新の内容は原文をご確認ください。

Python パターン

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

使用する場面

Python のアーキテクチャ判断、フレームワークの選択、非同期パターンの設計、Python プロジェクトの構成を行うときに、このスキルを使用します。


⚠️ このスキルの使い方

このスキルが教えるのは、コピーするための固定コードではなく、意思決定の原則です。

  • 不明な場合は、ユーザーにフレームワークの好みを尋ねる
  • 非同期か同期かは CONTEXT に基づいて選ぶ
  • 毎回同じフレームワークをデフォルトにしない

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シンプル、学習用
非同期ネイティブDjango 5.0+拡張機能経由
管理画面手動組み込み拡張機能経由
ORM自由に選択Django ORM自由に選択
学習曲線低い中程度低い
尋ねるべき選択の質問:
  1. これは API 専用ですか、それともフルスタックですか?
  2. 管理インターフェースは必要ですか?
  3. チームは非同期に慣れていますか?
  4. 既存のインフラストラクチャはありますか?

2. 非同期 vs 同期の判断

非同期を使う場面
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
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 の非同期 (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 パターンとは、あなた固有のコンテキストに対する意思決定です。コードをコピーするのではなく、あなたのアプリケーションに最適なものを考えましょう。

制限事項

  • このスキルは、タスクが上記のスコープに明確に一致する場合にのみ使用してください。
  • 出力を、環境固有の検証、テスト、専門家によるレビューの代替として扱わないでください。
  • 必要な入力、権限、安全境界、成功基準が欠けている場合は、作業を中断して確認を求めてください。

コメント