mcpField
C
coding-standards

coding-standards

github.com/ludo-technologies開発3447 回インストール2 週間前に更新
リポジトリ

coding-standards について

AI エージェントや LLM 向けの Python コーディング規約集です。パフォーマンス、非同期処理、設計、ドキュメント、検証、オブジェクト指向の指針を例とともにまとめています。

主な機能

  1. 01エラー処理の規則
  2. 02パフォーマンス最適化パターン
  3. 03非同期処理の指針
  4. 04設計と SOLID 原則
  5. 05ドキュメントと型ヒント

活用シーン

  1. 01Python コード生成の指針
  2. 02Python の実装パターンの確認
  3. 03非同期リソース管理の実践
  4. 04公開 API ドキュメントの標準化

インストール

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

$npx skills add https://github.com/ludo-technologies/python-best-practices --skill coding-standards

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

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

metadata.json
README.md
rules/
_sections.md
_template.md
async-context-manager.md
async-create-task.md
async-gather.md
async-semaphore.md
design-dependency-injection.md
design-early-return.md
design-no-global-singleton.md
design-philosophy.md
design-pure-functions.md
design-single-responsibility.md
doc-docstring.md
doc-type-hints.md
error-no-silent-exceptions.md
oop-composition-over-inheritance.md
oop-dataclass.md
oop-property.md
oop-protocol.md
perf-dict-get.md
perf-generator-expression.md
perf-list-comprehension.md
perf-set-lookup.md
perf-str-join.md
solid-isp.md
solid-lsp.md
solid-ocp.md
validation-pydantic.md

詳細

Python コーディング標準

Python コーディング標準とベストプラクティスを包括的にまとめています。AI エージェントや LLM が、高品質で高性能、かつ保守しやすい Python コードを生成できるよう設計されています。

カテゴリー

エラー処理 [CRITICAL]

失敗が隠されたり、成功したかのように報告されたりするのを防ぎます。

ルール説明
error-no-silent-exceptions例外を握りつぶさない
パフォーマンス最適化 [CRITICAL]

Python の最適化パターンを適用して、処理速度とメモリ効率を向上させます。

ルール説明
perf-list-comprehensionループよりリスト内包表記を優先する(1.5~2 倍高速)
perf-generator-expression大規模なデータセットにはジェネレーターを使用する(メモリ使用量 O(1))
perf-dict-get効率的にデフォルト値を取得するには dict.get() を使用する
perf-set-lookup高速な検索には set を使用する(O(n) に対して O(1))
perf-str-join文字列の連結には join を使用する(O(n²) に対して O(n))
非同期処理 [HIGH]

asyncio を使用した効率的な非同期プログラミングのパターンです。

ルール説明
async-gather独立したタスクには asyncio.gather を使用する
async-create-taskバックグラウンドタスクを適切に作成する
async-context-managerasync with でリソースを管理する
async-semaphoreセマフォで同時実行数を制限する
設計原則 [HIGH]

保守性と拡張性を高めるソフトウェア設計原則です。

ルール説明
design-philosophyDRY、YAGNI、KISS の原則
design-single-responsibility単一責任の原則
design-dependency-injection依存性注入による疎結合
design-no-global-singletonグローバルなシングルトンやモジュールレベルの共有インスタンスを避ける
solid-ocpオープン・クローズドの原則
solid-lspリスコフの置換原則
solid-ispインターフェース分離の原則
design-pure-functions副作用のない純粋関数を優先する
design-early-return早期リターンでネストを減らす
ドキュメント [HIGH]

公開 API の明確さと、機械で検証可能な契約のためのドキュメント標準です。

ルール説明
doc-docstringGoogle スタイルの docstring で公開 API を文書化する
doc-type-hints公開 API に型ヒントを必須とする
データ検証 [HIGH]

信頼境界を越えるデータの検証パターンです。

ルール説明
validation-pydantic境界データの検証に Pydantic を使用する
オブジェクト指向プログラミング [MEDIUM]

Python らしいオブジェクト指向プログラミングのベストプラクティスです。

ルール説明
oop-composition-over-inheritance継承よりコンポジションを優先する
oop-dataclassデータコンテナーには dataclass を使用する
oop-protocol抽象基底クラスより Protocol を優先する
oop-propertygetter の代わりに property を使用する

クイックリファレンス

エラー処理
try:
    config = parse_config(path)
except ConfigParseError as exc:
    raise StartupError(f"Invalid configuration: {path}") from exc


def main() -> int:
    try:
        start_application()
    except StartupError:
        logger.exception("Application startup failed")
        return 1  # explicit non-success outcome at the process boundary
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
パフォーマンスパターン
# List comprehension (not loops)
result = [x * 2 for x in items]

# Generator for large data
total = sum(x * x for x in range(1_000_000))

# dict.get() with default
value = config.get("key", default_value)

# Set for fast lookup
valid_ids: set[int] = {1, 2, 3}
if item_id in valid_ids: ...

# join for strings
result = ",".join(values)
非同期処理パターン
# Concurrent execution
results = await asyncio.gather(task1(), task2(), task3())

# Resource management
async with aiohttp.ClientSession() as session:
    async with session.get(url) as response:
        data = await response.json()

# Concurrency limit
semaphore = asyncio.Semaphore(10)
async with semaphore:
    await do_work()
設計パターン
# Dependency injection (not module-level singletons)
class Service:
    def __init__(self, repository: Repository) -> None:
        self.repository = repository

# Composition root builds the graph once
def create_app(settings: Settings) -> Service:
    return Service(repository=PostgresRepository(settings.dsn))

# Open/Closed: extend via new types, not edits
class JsonFormat:
    def export(self, invoice: Invoice) -> str: ...

# Interface Segregation: small Protocols
class Workable(Protocol):
    def work(self) -> None: ...

# Early return
def process(data: Data | None) -> Result:
    if data is None:
        return Result.empty()
    # main logic here
ドキュメントパターン
def create_user(email: str, name: str) -> User:
    """Create a user account.

    Args:
        email: Unique email address for the account.
        name: Display name for the user.

    Returns:
        The created user.
    """
    return user_repository.create(email=email, name=name)
検証パターン
from pydantic import BaseModel, EmailStr, Field

class CreateUserRequest(BaseModel):
    email: EmailStr
    age: int = Field(ge=0, le=150)
OOP パターン
# Dataclass
@dataclass
class User:
    name: str
    email: str

# Protocol for interfaces
class Repository(Protocol):
    def get(self, id: str) -> Entity: ...

# Property
@property
def full_name(self) -> str:
    return f"{self.first} {self.last}"

関連項目

  • 推奨ツール - これらの標準を自動的に適用するツール(ruff、mypy、pytest、pyscn、uv)

コメント