mcpField
P
python-code-style

python-code-style

github.com/wshobson開発41.9k16.7k 回インストール2 週間前に更新
リポジトリ

python-code-style について

Pythonのコードスタイルとドキュメントの標準化を支援するスキルです。リンティング、フォーマット、型チェック、命名規則、保守しやすいプロジェクト文書を扱います。

主な機能

  1. 01ruffのフォーマットとリンティング設定
  2. 02mypyまたはpyrightの型チェック設定
  3. 03PEP 8の命名規則
  4. 04一貫したインポート整理
  5. 05GoogleスタイルのDocstring指針
  6. 06プロジェクト文書の作成指針

活用シーン

  1. 01Pythonプロジェクトのツール設定
  2. 02コードスタイルの一貫性確認
  3. 03公開APIのDocstring作成
  4. 04チームのコーディング規約策定

インストール

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

$npx skills add https://github.com/wshobson/agents --skill python-code-style

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

詳細

Python のコードスタイルとドキュメント

一貫したコードスタイルと明確なドキュメントは、コードベースを保守しやすくし、共同作業を円滑にします。このスキルでは、モダンな Python のツール、命名規則、ドキュメントの標準について扱います。

このスキルを使う場面

  • 新しいプロジェクトのリンティングとフォーマットを設定するとき
  • docstring を書いたりレビューしたりするとき
  • チームのコーディング標準を策定するとき
  • ruff、mypy、pyright を設定するとき
  • スタイルの一貫性の観点でコードをレビューするとき
  • プロジェクトのドキュメントを作成するとき

中核となる概念

1. 自動フォーマット

フォーマットの議論はツールに任せましょう。一度設定すれば、自動的に適用されます。

2. 一貫した命名

意味のある説明的な名前をつけ、PEP 8 の規約に従います。

3. コードとしてのドキュメント

docstring は、それが説明するコードと一緒にメンテナンスされるべきです。

4. 型アノテーション

モダンな Python コードでは、すべての公開 API に型ヒントを含めるべきです。

クイックスタート

# Install modern tooling
pip install ruff mypy

# Configure in pyproject.toml
[tool.ruff]
line-length = 120
target-version = "py312"  # Adjust based on your project's minimum Python version

[tool.mypy]
strict = true

基本的なパターン

パターン 1: モダンな Python ツール

ruff をオールインワンのリンター兼フォーマッターとして使用します。flake8、isort、black を単一の高速なツールで置き換えます。

# pyproject.toml
[tool.ruff]
line-length = 120
target-version = "py312"  # Adjust based on your project's minimum Python version

[tool.ruff.lint]
select = [
    "E",    # pycodestyle errors
    "W",    # pycodestyle warnings
    "F",    # pyflakes
    "I",    # isort
    "B",    # flake8-bugbear
    "C4",   # flake8-comprehensions
    "UP",   # pyupgrade
    "SIM",  # flake8-simplify
]
ignore = ["E501"]  # Line length handled by formatter

[tool.ruff.format]
quote-style = "double"
indent-style = "space"

次のように実行します:

ruff check --fix .  # Lint and auto-fix
ruff format .       # Format code
パターン 2: 型チェックの設定

本番コード向けに厳格な型チェックを設定します。

# pyproject.toml
[tool.mypy]
python_version = "3.12"
strict = true
warn_return_any = true
warn_unused_ignores = true
disallow_untyped_defs = true
disallow_incomplete_defs = true

[[tool.mypy.overrides]]
module = "tests.*"
disallow_untyped_defs = false

代替案: より高速なチェックが必要な場合は pyright を使用します。

[tool.pyright]
pythonVersion = "3.12"
typeCheckingMode = "strict"
パターン 3: 命名規則

簡潔さよりも明確さを重視して、PEP 8 に従います。

ファイルとモジュール:

# Good: Descriptive snake_case
user_repository.py
order_processing.py
http_client.py

# Avoid: Abbreviations
usr_repo.py
ord_proc.py
http_cli.py

クラスと関数:

# Classes: PascalCase
class UserRepository:
    pass

class HTTPClientFactory:  # Acronyms stay uppercase
    pass

# Functions and variables: snake_case
def get_user_by_email(email: str) -> User | None:
    retry_count = 3
    max_connections = 100

定数:

# Module-level constants: SCREAMING_SNAKE_CASE
MAX_RETRY_ATTEMPTS = 3
DEFAULT_TIMEOUT_SECONDS = 30
API_BASE_URL = "https://api.example.com"
パターン 4: インポートの整理

インポートは一貫した順序でグループ化します: 標準ライブラリ、サードパーティ、ローカル。

# Standard library
import os
from collections.abc import Callable
from typing import Any

# Third-party packages
import httpx
from pydantic import BaseModel
from sqlalchemy import Column

# Local imports
from myproject.models import User
from myproject.services import UserService

絶対インポートのみを使用します:

# Preferred
from myproject.utils import retry_decorator

# Avoid relative imports
from ..utils import retry_decorator

応用的なパターン

パターン 5: Google スタイルの docstring

すべての公開クラス、メソッド、関数に docstring を書きます。

シンプルな関数:

def get_user(user_id: str) -> User:
    """Retrieve a user by their unique identifier."""
    ...

複雑な関数:

def process_batch(
    items: list[Item],
    max_workers: int = 4,
    on_progress: Callable[[int, int], None] | None = None,
) -> BatchResult:
    """Process items concurrently using a worker pool.

    Processes each item in the batch using the configured number of
    workers. Progress can be monitored via the optional callback.

    Args:
        items: The items to process. Must not be empty.
        max_workers: Maximum concurrent workers. Defaults to 4.
        on_progress: Optional callback receiving (completed, total) counts.

    Returns:
        BatchResult containing succeeded items and any failures with
        their associated exceptions.

    Raises:
        ValueError: If items is empty.
        ProcessingError: If the batch cannot be processed.

    Example:
        >>> result = process_batch(items, max_workers=8)
        >>> print(f"Processed {len(result.succeeded)} items")
    """
    ...

クラスの docstring:

class UserService:
    """Service for managing user operations.

    Provides methods for creating, retrieving, updating, and
    deleting users with proper validation and error handling.

    Attributes:
        repository: The data access layer for user persistence.
        logger: Logger instance for operation tracking.

    Example:
        >>> service = UserService(repository, logger)
        >>> user = service.create_user(CreateUserInput(...))
    """

    def __init__(self, repository: UserRepository, logger: Logger) -> None:
        """Initialize the user service.

        Args:
            repository: Data access layer for users.
            logger: Logger for tracking operations.
        """
        self.repository = repository
        self.logger = logger
パターン 6: 行の長さとフォーマット

モダンなディスプレイに合わせて、読みやすさを維持しつつ行の長さを 120 文字に設定します。

# Good: Readable line breaks
def create_user(
    email: str,
    name: str,
    role: UserRole = UserRole.MEMBER,
    notify: bool = True,
) -> User:
    ...

# Good: Chain method calls clearly
result = (
    db.query(User)
    .filter(User.active == True)
    .order_by(User.created_at.desc())
    .limit(10)
    .all()
)

# Good: Format long strings
error_message = (
    f"Failed to process user {user_id}: "
    f"received status {response.status_code} "
    f"with body {response.text[:100]}"
)
パターン 7: プロジェクトのドキュメント

README の構成:

# Project Name

Brief description of what the project does.

## Installation

\`\`\`bash
pip install myproject
\`\`\`

## Quick Start

\`\`\`python
from myproject import Client

client = Client(api_key="...")
result = client.process(data)
\`\`\`

## Configuration

Document environment variables and configuration options.

## Development

\`\`\`bash
pip install -e ".[dev]"
pytest
\`\`\`

CHANGELOG のフォーマット (Keep a Changelog):

# Changelog

## [Unreleased]

### Added
- New feature X

### Changed
- Modified behavior of Y

### Fixed
- Bug in Z

ベストプラクティスのまとめ

  1. ruff を使う - リンティングとフォーマットを単一のツールで
  2. 厳格な mypy を有効にする - 実行時より前に型エラーを検出
  3. 120 文字の行 - 読みやすさのためのモダンな標準
  4. 説明的な名前 - 簡潔さよりも明確さ
  5. 絶対インポート - 相対インポートよりも保守しやすい
  6. Google スタイルの docstring - 一貫性があり読みやすいドキュメント
  7. 公開 API を文書化する - すべての公開関数に docstring が必要
  8. ドキュメントを最新に保つ - ドキュメントをコードとして扱う
  9. CI で自動化する - コミットごとにリンターを実行
  10. Python 3.10+ を対象にする - 新しいプロジェクトでは、モダンな言語機能のために Python 3.12+ を推奨

コメント