python-code-style について
python-code-styleは、Pythonコードの作成、レビュー、標準化に取り組む開発者向けのスキルです。命名、フォーマット、リンティング、型チェック、インポート、ドキュメントを扱い、ruff、mypy、pyrightなどの例を含みます。
主な機能
- 01ruffによる整形とリンティング
- 02mypyとpyrightの設定
- 03PEP 8の命名規則
- 04インポート整理の実践
- 05Googleスタイルのdocstring指針
- 06公開APIの型注釈指針
活用シーン
- 01Pythonのリンティングと整形の設定
- 02コードスタイルの一貫性をレビュー
- 03チームのPython規約を策定
- 04APIドキュメントを作成・レビュー
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ full-stack-skills/ python-skills --skill python-code-styleインストール後、Claude Code で/python-code-styleを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
LICENSE.txtagents/openai.yamlexamples/advanced-usage.mdbasic-usage.mdintegration.md詳細
出典:このスキルの内容は wshobson/agents に由来します(MIT License、Copyright (c) 2024 Seth Hobson。ライセンス全文は同じディレクトリの
LICENSE.txtをご覧ください)。 使用、変更、再配布は MIT ライセンスの条項に従い、著作権表示を保持する必要があります。
日本語の説明
このスキルでは、フルスタック開発に関するベストプラクティスとパターンを案内します。
name: python-code-style description: Python のコードスタイル、リンティング、フォーマット、命名規則、ドキュメントの標準を扱います。新しいコードの作成、スタイルのレビュー、リンターの設定、docstring の記述、プロジェクト標準の策定に使用します。
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 を厳格モードで有効にする - 実行時に入る前に型エラーを検出します
- 1 行を 120 文字にする - 読みやすさを保つための最新の標準です
- 説明的な名前を付ける - 簡潔さより明確さを重視します
- 絶対インポートを使用する - 相対インポートより保守しやすくなります
- Google スタイルの docstring を使用する - 一貫性があり、読みやすいドキュメントになります
- 公開 API をドキュメント化する - すべての公開関数に docstring が必要です
- ドキュメントを最新に保つ - ドキュメントをコードとして扱います
- CI で自動化する - すべてのコミットでリンターを実行します
- Python 3.10 以降を対象にする - 新規プロジェクトでは、最新の言語機能を利用できる Python 3.12 以降を推奨します
能力の範囲
✅ 得意なこと
- フルスタック開発に関するベストプラクティス
- コードアーキテクチャの設計ガイダンス
- パフォーマンス最適化の提案
⚠️ 必要な情報
- プロジェクトの具体的なコンテキスト
- 技術スタックの情報
❌ 対応範囲外
- 技術以外の分野におけるビジネス上の意思決定
- 具体的なコードの実装(ガイダンスのみを提供)
ワークフロー
ステップ 1:要件分析
プロジェクトの要件と技術的制約を理解します
ステップ 2:アーキテクチャ設計
システムアーキテクチャとコンポーネントの分割を設計します
ステップ 3:実装ガイダンス
具体的な実装の提案とコードパターンを提示します
ステップ 4:コードレビュー
コードの品質とベストプラクティスの遵守状況をレビューします
ステップ 5:最適化の提案
パフォーマンスの最適化と改善の提案を行います
注意点
1. 過剰設計
単純な場面で複雑なデザインパターンを使うのは避けてください
2. パフォーマンスへの配慮不足
特に本番環境では、パフォーマンスの最適化を軽視しないでください
3. セキュリティへの配慮
常にセキュリティとデータ保護を考慮してください
4. テストカバレッジ
特に境界条件について、十分なテストカバレッジを確保してください
5. ドキュメントの保守
ドキュメントをコードと同期した状態に保ってください