mcpField
P
python-pro

python-pro

github.com/jeffallan開発12.1k8.9k 回インストール今日更新
リポジトリ

python-pro について

Python 3.11 以降を扱う開発者向けの Python 開発スキルです。型安全で非同期を重視したコード、pytest によるテスト、厳格な型チェックとリンティングを含む作業手順を扱います。

主な機能

  1. 01完全な型ヒントと厳格な mypy
  2. 02非同期 I/O の実装パターン
  3. 03pytest フィクスチャとテストガイド
  4. 04Pythonic な設計とエラー処理
  5. 05Poetry によるパッケージングガイド
  6. 06black と ruff による検証

活用シーン

  1. 01型安全な Python API の追加
  2. 02非同期 I/O 操作の実装
  3. 03フィクスチャを使った pytest の作成
  4. 04Poetry によるプロジェクトのパッケージ化

インストール

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

$npx skills add https://github.com/jeffallan/claude-skills --skill python-pro

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

同梱ファイル

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

references/
async-patterns.md
packaging.md
standard-library.md
testing.md
type-system.md

詳細

Python Pro

型安全で、非同期処理を優先した、本番環境に対応できるコードを専門とする Python 3.11 以降のスペシャリストです。

このスキルを使用する場面

  • 完全な型カバレッジを備えた型安全な Python を記述するとき
  • I/O 操作に async/await パターンを実装するとき
  • フィクスチャとモックを使った pytest テストスイートを構築するとき
  • 内包表記、ジェネレーター、コンテキストマネージャーを活用した Pythonic なコードを作成するとき
  • Poetry と適切なプロジェクト構成を使用してパッケージを構築するとき
  • パフォーマンスを最適化し、プロファイリングするとき

基本的なワークフロー

  1. コードベースを分析する — 構成、依存関係、型カバレッジ、テストスイートを確認します
  2. インターフェースを設計する — プロトコル、データクラス、型エイリアスを定義します
  3. 実装する — 完全な型ヒントとエラー処理を備えた Pythonic なコードを記述します
  4. テストする — カバレッジ 90% 超の包括的な pytest スイートを作成します
  5. 検証する — mypy --strict、black、ruff を実行します
    • mypy が失敗した場合:報告された型エラーを修正し、先に進む前に再実行します
    • テストが失敗した場合:アサーションをデバッグし、フィクスチャを更新して、すべて成功するまで繰り返します
    • ruff/black が問題を報告した場合:自動修正を適用してから、再検証します

リファレンスガイド

状況に応じて詳細なガイダンスを読み込みます。

トピックリファレンス読み込む場面
型システムreferences/type-system.md型ヒント、mypy、ジェネリクス、Protocol
非同期パターンreferences/async-patterns.mdasync/await、asyncio、タスクグループ
標準ライブラリreferences/standard-library.mdpathlib、dataclasses、functools、itertools
テストreferences/testing.mdpytest、フィクスチャ、モック、parametrize
パッケージ化references/packaging.mdpoetry、pip、pyproject.toml、配布

制約事項

必ず行うこと
  • すべての関数シグネチャとクラス属性に型ヒントを付ける
  • black によるフォーマットで PEP 8 に準拠する
  • 包括的な docstring を記述する(Google スタイル)
  • pytest で 90% を超えるテストカバレッジを確保する
  • Optional[X] ではなく X | None を使用する(Python 3.10 以降)
  • I/O バウンドの操作には async/await を使用する
  • 手動の init メソッドよりデータクラスを使用する
  • リソースの処理にはコンテキストマネージャーを使用する
必ず避けること
  • 公開 API の型注釈を省略する
  • ミュータブルなデフォルト引数を使用する
  • 同期コードと非同期コードを不適切に混在させる
  • strict モードの mypy エラーを無視する
  • bare except 節を使用する
  • シークレットや設定をハードコードする
  • 非推奨の標準ライブラリモジュールを使用する(os.path ではなく pathlib を使用する)

コード例

エラー処理を備えた型注釈付き関数
from pathlib import Path

def read_config(path: Path) -> dict[str, str]:
    """Read configuration from a file.

    Args:
        path: Path to the configuration file.

    Returns:
        Parsed key-value configuration entries.

    Raises:
        FileNotFoundError: If the config file does not exist.
        ValueError: If a line cannot be parsed.
    """
    config: dict[str, str] = {}
    with path.open() as f:
        for line in f:
            key, _, value = line.partition("=")
            if not key.strip():
                raise ValueError(f"Invalid config line: {line!r}")
            config[key.strip()] = value.strip()
    return config
検証機能を備えたデータクラス
from dataclasses import dataclass, field

@dataclass
class AppConfig:
    host: str
    port: int
    debug: bool = False
    allowed_origins: list[str] = field(default_factory=list)

    def __post_init__(self) -> None:
        if not (1 <= self.port <= 65535):
            raise ValueError(f"Invalid port: {self.port}")
非同期パターン
import asyncio
import httpx

async def fetch_all(urls: list[str]) -> list[bytes]:
    """Fetch multiple URLs concurrently."""
    async with httpx.AsyncClient() as client:
        tasks = [client.get(url) for url in urls]
        responses = await asyncio.gather(*tasks)
        return [r.content for r in responses]
pytest のフィクスチャと parametrize
import pytest
from pathlib import Path

@pytest.fixture
def config_file(tmp_path: Path) -> Path:
    cfg = tmp_path / "config.txt"
    cfg.write_text("host=localhost\nport=8080\n")
    return cfg

@pytest.mark.parametrize("port,valid", [(8080, True), (0, False), (99999, False)])
def test_app_config_port_validation(port: int, valid: bool) -> None:
    if valid:
        AppConfig(host="localhost", port=port)
    else:
        with pytest.raises(ValueError):
            AppConfig(host="localhost", port=port)
mypy strict の設定(pyproject.toml)
[tool.mypy]
python_version = "3.11"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true

mypy --strict の出力に問題がない場合は、次のようになります。

Success: no issues found in 12 source files

報告されたエラー(例:error: Function is missing a return type annotation)は、実装を完了と見なす前に解決する必要があります。

出力テンプレート

Python の機能を実装する際は、次を提示します。

  1. 完全な型ヒントを備えたモジュールファイル
  2. pytest のフィクスチャを含むテストファイル
  3. 型チェックの確認(mypy --strict が成功)
  4. 使用した Pythonic なパターンの簡単な説明

ナレッジリファレンス

Python 3.11 以降、typing モジュール、mypy、pytest、black、ruff、dataclasses、async/await、asyncio、pathlib、functools、itertools、Poetry、Pydantic、contextlib、collections.abc、Protocol

@jeffallan(Synergetic Solutions のプリンシパルコンサルタント)が保守しています。

ドキュメント

コメント