mcpField
G
gravitas-python

gravitas-python

github.com/udaysharmadev开发384271 次安装今天更新
代码仓库

关于 gravitas-python

面向 Python 项目的 GRAVITAS 技能扩展,供遵循基础 GRAVITAS 技能的编码 Agent 使用。它补充项目检查、验证流程、测试模式和常见错误防范指南。

主要功能

  1. 01Python 项目结构检查
  2. 02mypy、ruff 和 pytest 验证
  3. 03Python 反模式指南
  4. 04pytest fixture 与测试模式
  5. 05FastAPI 和 Django 说明

适用场景

  1. 01检查 Python 项目配置
  2. 02按统一顺序运行 Python 检查
  3. 03避免常见类型与异常错误
  4. 04为 Web 框架编写 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:
对于结构化数据,使用 dataclasses 或 Pydantic,而非 dict
BAD:  return {"user_id": 1, "name": "Alice"}   # no type safety
GOOD: return UserResponse(user_id=1, name="Alice")

常见 Python 故障模式

故障根本原因修复方法
Optional[X] has no attribute Y未处理 None添加 if x is not None: 守卫
Incompatible return value type返回类型错误检查函数签名
Missing return statement并非所有路径都有返回值添加显式返回语句
Module has no attribute X导入错误使用 dir(module) 检查模块
Cannot find implementation for X缺少存根安装 types-X 包
循环导入在模块级别导入移至函数级别或重构

测试模式(pytest)

Fixture 模式
# 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

评论

支持 Markdown