mcpField
G
gravitas-python

gravitas-python

github.com/udaysharmadev開発384271 回インストール今日更新
リポジトリ

gravitas-python について

Python プロジェクト向けの GRAVITAS 拡張スキルで、ベースの GRAVITAS スキルに従うコーディングエージェントを対象としています。プロジェクト調査、検証手順、テストパターン、よくあるミスの防止策を補います。

主な機能

  1. 01Python プロジェクトの調査
  2. 02mypy、ruff、pytest による検証
  3. 03Python のアンチパターン指針
  4. 04pytest のフィクスチャとテストパターン
  5. 05FastAPI と Django の注意点

活用シーン

  1. 01Python プロジェクト設定の確認
  2. 02統一した順序での検証実行
  3. 03型や例外に関するミスの回避
  4. 04Web フレームワークの pytest 作成

インストール

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

$npx skills add https://github.com/udaysharmadev/gravitas --skill gravitas-python

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

詳細

GRAVITAS — Python 拡張

ベースとなる GRAVITAS スキルを、Python 固有のパターンで拡張します。 まず skills/gravitas/SKILL.md を読み込んでから、このファイルを読み込んでください。


Python の調査に関する追加事項

□ pyproject.toml — [tool.mypy], [tool.ruff], [tool.pytest.ini_options]
□ setup.py / setup.cfg — legacy config
□ requirements.txt / requirements-dev.txt — dependency versions
□ conftest.py — pytest fixtures (critical for understanding test patterns)
□ __init__.py — package structure
□ Type stubs — are there py.typed markers? stub packages installed?
型の厳格さを確認するには pyproject.toml を読む
cat pyproject.toml | grep -A 10 "\[tool.mypy\]"
cat pyproject.toml | grep -A 10 "\[tool.ruff\]"

Python の検証チェーン

# Full chain — in this order
mypy . --strict                          # type correctness
ruff check .                             # lint (fast, Rust-based)
ruff format --check .                    # format check
pytest -v --tb=short                     # all tests

# With coverage
pytest --cov=src --cov-report=term-missing -v

# Type coverage
mypy . --strict 2>&1 | tail -5           # summary line shows error count

Python 固有のアンチパターン

裸の except は使用しない
BAD:  except:
GOOD: except ValueError as e:
GOOD: except (TypeError, ValueError) as e:
組み込み名をシャドーイングしない
BAD:  list = [1, 2, 3]     # shadows list()
BAD:  id = user.id         # shadows id()
GOOD: items = [1, 2, 3]
GOOD: user_id = user.id
型注釈を必須にする(mypy strict の場合)
BAD:  def process(data):
GOOD: def process(data: dict[str, Any]) -> ProcessResult:
構造化データには dict ではなく dataclasses または Pydantic を使用する
BAD:  return {"user_id": 1, "name": "Alice"}   # no type safety
GOOD: return UserResponse(user_id=1, name="Alice")

よくある Python の障害モード

障害根本原因修正方法
Optional[X] has no attribute YNone が処理されていないif x is not None: ガードを追加する
Incompatible return value type戻り値の型が誤っている関数シグネチャを確認する
Missing return statementすべての経路で戻り値が返されていない明示的な return を追加する
Module has no attribute Xインポートが誤っているdir(module) でモジュールを確認する
Cannot find implementation for Xスタブが不足しているtypes-X パッケージをインストールする
循環インポートモジュールレベルでのインポート関数レベルに移動するか、構成を見直す

テストパターン(pytest)

フィクスチャパターン
# conftest.py
import pytest
from myapp.db import get_db

@pytest.fixture
def db():
    conn = get_db(":memory:")
    yield conn
    conn.close()

@pytest.fixture
def client(db):
    from myapp import create_app
    app = create_app({"TESTING": True})
    with app.test_client() as c:
        yield c
標準的なテスト構成
class TestUserAuth:
    def test_login_success(self, client, db):
        # Arrange
        db.execute("INSERT INTO users VALUES (1, 'alice', 'hash')")
        # Act
        response = client.post("/login", json={"username": "alice", "password": "pw"})
        # Assert
        assert response.status_code == 200
        assert response.json["token"] is not None

    def test_login_wrong_password(self, client, db):
        response = client.post("/login", json={"username": "alice", "password": "wrong"})
        assert response.status_code == 401
エッジケースには Parametrize を使用する
@pytest.mark.parametrize("input,expected", [
    ("", ValueError),
    (None, TypeError),
    ("[email protected]", None),
    ("not-an-email", ValueError),
])
def test_validate_email(input, expected):
    if expected:
        with pytest.raises(expected):
            validate_email(input)
    else:
        validate_email(input)  # should not raise

フレームワーク固有の注意事項

FastAPI
# Always test with TestClient, not raw function calls
from fastapi.testclient import TestClient
client = TestClient(app)

# Type all path/query params and bodies
@router.post("/users", response_model=UserResponse)
async def create_user(body: CreateUserRequest) -> UserResponse:
    ...
Django
# Use pytest-django
# settings for tests
@pytest.mark.django_db
def test_user_creation():
    user = User.objects.create_user(username="test", password="pass")
    assert user.id is not None

クイックリファレンス

# Run single test file
pytest src/auth/test_session.py -v

# Run single test
pytest src/auth/test_session.py::TestSession::test_timeout -v

# Run with pdb on failure
pytest --pdb

# Show slowest tests
pytest --durations=10

# Type check single file
mypy src/auth/session.py --strict

コメント