mcpField
P
python-best-practices

python-best-practices

github.com/rohitg00開発2.8k210 回インストール25 週間前に更新
リポジトリ

python-best-practices について

Python 開発者向けのベストプラクティススキルです。型注釈、データモデル、非同期処理、プロジェクト設定、テスト、エラー処理を、実装例とともに扱います。

主な機能

  1. 01関数の型注釈と厳格なチェック
  2. 02Dataclasses と Pydantic の使い分け
  3. 03非同期 I/O と並行処理パターン
  4. 04プロジェクト構成と pyproject.toml
  5. 05pytest のテストパターン
  6. 06Python の慣用表現とエラー処理

活用シーン

  1. 01Python プロジェクトの規約策定
  2. 02非同期 HTTP とリソース管理の確認
  3. 03内部・外部データモデルの選択
  4. 04テストと例外処理の構成

インストール

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

$npx skills add https://github.com/rohitg00/awesome-claude-code-toolkit --skill python-best-practices

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

詳細

Python のベストプラクティス

型ヒント(3.12 以降の構文)

# Use built-in generics (3.9+), no need for typing.List, typing.Dict
def process_items(items: list[str]) -> dict[str, int]:
    return {item: len(item) for item in items}

# Union with | syntax (3.10+)
def find_user(user_id: int) -> User | None:
    ...

# Type parameter syntax (3.12+)
type Vector[T] = list[T]
type Matrix[T] = list[Vector[T]]

def first[T](items: list[T]) -> T:
    return items[0]

# TypedDict for structured dicts
from typing import TypedDict

class UserResponse(TypedDict):
    id: int
    name: str
    email: str
    active: bool

関数シグネチャには必ず型を指定してください。CI では mypy --strict または pyright を使用してください。正当な理由がある場合に限り、type: ignore コメントを使用してください。

Dataclass と Pydantic の使い分け

Dataclass(内部データ、検証不要)
from dataclasses import dataclass, field

@dataclass(frozen=True, slots=True)
class Point:
    x: float
    y: float

    def distance_to(self, other: "Point") -> float:
        return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5

@dataclass
class Config:
    host: str = "localhost"
    port: int = 8080
    tags: list[str] = field(default_factory=list)

不変の値オブジェクトには frozen=True を使用してください。メモリ効率を高めるには slots=True を使用してください。

Pydantic(外部入力、検証が必要)
from pydantic import BaseModel, Field, field_validator

class CreateUserRequest(BaseModel):
    model_config = {"strict": True}

    email: str = Field(max_length=255)
    name: str = Field(min_length=1, max_length=100)
    age: int = Field(ge=13, le=150)

    @field_validator("email")
    @classmethod
    def validate_email(cls, v: str) -> str:
        if "@" not in v:
            raise ValueError("Invalid email format")
        return v.lower()

ルール:ドメインモデルと内部構造体には dataclass を使用してください。API 境界、設定ファイル、外部データの解析には Pydantic を使用してください。

非同期処理のパターン

import asyncio
import httpx

async def fetch_user(client: httpx.AsyncClient, user_id: int) -> User:
    response = await client.get(f"/users/{user_id}")
    response.raise_for_status()
    return User(**response.json())

async def fetch_all_users(user_ids: list[int]) -> list[User]:
    async with httpx.AsyncClient(base_url="https://api.example.com") as client:
        tasks = [fetch_user(client, uid) for uid in user_ids]
        return await asyncio.gather(*tasks)

async def process_with_semaphore(items: list[str], max_concurrent: int = 10):
    semaphore = asyncio.Semaphore(max_concurrent)
    async def bounded_process(item: str):
        async with semaphore:
            return await process_item(item)
    return await asyncio.gather(*[bounded_process(i) for i in items])

ルール:

  • 非同期 HTTP には requests ではなく httpx を使用してください
  • 並行タスクには asyncio.gather を、レート制限には asyncio.Semaphore を使用してください
  • 非同期関数内でブロッキング I/O を呼び出さないでください(レガシーコードには asyncio.to_thread を使用してください)
  • リソース(接続、セッション)の管理には async with を使用してください

プロジェクト構成

my-project/
  src/
    my_project/
      __init__.py
      main.py
      models.py
      services/
        __init__.py
        user_service.py
      api/
        __init__.py
        routes.py
  tests/
    conftest.py
    test_models.py
    test_services/
      test_user_service.py
  pyproject.toml

プロジェクトのルートから誤ってインポートされるのを防ぐため、src レイアウトを使用してください。

pyproject.toml

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "my-project"
version = "1.0.0"
requires-python = ">=3.12"
dependencies = [
    "httpx>=0.27",
    "pydantic>=2.0",
]

[project.optional-dependencies]
dev = [
    "pytest>=8.0",
    "pytest-cov",
    "pytest-asyncio",
    "mypy",
    "ruff",
]

[project.scripts]
my-project = "my_project.main:cli"

[tool.ruff]
line-length = 100
target-version = "py312"

[tool.ruff.lint]
select = ["E", "F", "I", "N", "UP", "B", "SIM", "RUF"]

[tool.mypy]
strict = true

[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]

すべてのツールの設定には pyproject.toml を使用してください。flake8、isort、black の代わりに Ruff を使用してください(単一のツールで、10~100 倍高速です)。

仮想環境

# Use uv for fast dependency management
uv venv
uv pip install -e ".[dev]"

# Or standard venv
python -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"

必ず仮想環境を使用してください。パッケージをグローバルにインストールしないでください。ロックファイル(uv.lock、または pip freeze から生成した requirements.txt)で正確なバージョンを固定してください。

pytest によるテスト

import pytest
from unittest.mock import AsyncMock, patch

@pytest.fixture
def user_service(db_session):
    return UserService(session=db_session)

async def test_create_user_returns_user_with_hashed_password(user_service):
    user = await user_service.create(email="[email protected]", password="secret")
    assert user.email == "[email protected]"
    assert user.password_hash != "secret"

async def test_create_user_rejects_duplicate_email(user_service):
    await user_service.create(email="[email protected]", password="secret")
    with pytest.raises(DuplicateEmailError):
        await user_service.create(email="[email protected]", password="other")

@pytest.fixture
def mock_http_client():
    client = AsyncMock(spec=httpx.AsyncClient)
    client.get.return_value = httpx.Response(200, json={"id": 1, "name": "Alice"})
    return client

async def test_fetch_user_parses_response(mock_http_client):
    user = await fetch_user(mock_http_client, user_id=1)
    assert user.name == "Alice"
    mock_http_client.get.assert_called_once_with("/users/1")

共有フィクスチャには conftest.py を使用してください。テストのバリエーションには pytest.mark.parametrize を使用してください。ファイルシステムのテストには tmp_path フィクスチャを使用してください。

Python らしいイディオム

# Unpacking
first, *rest = items
x, y = point

# Comprehensions over map/filter
squares = [x**2 for x in numbers if x > 0]
lookup = {u.id: u for u in users}

# Context managers for resource cleanup
with open(path) as f:
    data = f.read()

# Walrus operator for assign-and-test
if (match := pattern.search(text)) is not None:
    process(match.group(1))

# Structural pattern matching (3.10+)
match command:
    case {"action": "move", "direction": d}:
        move(d)
    case {"action": "quit"}:
        sys.exit(0)
    case _:
        raise ValueError(f"Unknown command: {command}")

エラー処理

class AppError(Exception):
    def __init__(self, message: str, code: str):
        super().__init__(message)
        self.code = code

class NotFoundError(AppError):
    def __init__(self, resource: str, id: str):
        super().__init__(f"{resource} {id} not found", "NOT_FOUND")

# Specific exceptions, never bare except
try:
    user = await get_user(user_id)
except NotFoundError:
    return {"error": "User not found"}, 404
except DatabaseError as e:
    logger.exception("Database error fetching user")
    return {"error": "Internal error"}, 500

裸の except: は使用しないでください。最も具体的な例外を捕捉してください。トレースバックを含めるには logger.exception() を使用してください。アプリケーション用のカスタム例外階層を定義してください。

コメント