python-code-style について
python-code-styleは、Pythonのコーディング規約とドキュメント基準を整える開発者向けのスキルです。フォーマット、命名、型チェック、インポート、ドキュメント作成を扱います。
主な機能
- 01Ruffによるリントとフォーマット
- 02mypyとpyrightによる型チェック
- 03PEP 8の命名規則
- 04インポートの整理方法
- 05Googleスタイルのdocstring
- 06プロジェクト文書の作成指針
活用シーン
- 01Pythonプロジェクトの検査と整形を設定
- 02コードスタイルの一貫性をレビュー
- 03厳格な型チェックを設定
- 04APIドキュメントを作成・改訂
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ julianobarbosa/ claude-code-skills --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
ベストプラクティスのまとめ
- ruff を使う - リンティングとフォーマットを単一のツールで
- 厳格な mypy を有効にする - 実行時より前に型エラーを検出
- 120 文字の行 - 読みやすさのためのモダンな標準
- 説明的な名前 - 簡潔さよりも明確さ
- 絶対インポート - 相対インポートよりも保守しやすい
- Google スタイルの docstring - 一貫性があり読みやすいドキュメント
- 公開 API を文書化する - すべての公開関数に docstring が必要
- ドキュメントを最新に保つ - ドキュメントをコードとして扱う
- CI で自動化する - コミットごとにリンターを実行
- Python 3.10+ を対象にする - 新しいプロジェクトでは、モダンな言語機能のために Python 3.12+ を推奨