关于 gravitas-python
面向 Python 项目的 GRAVITAS 技能扩展,供遵循基础 GRAVITAS 技能的编码 Agent 使用。它补充项目检查、验证流程、测试模式和常见错误防范指南。
主要功能
- 01Python 项目结构检查
- 02mypy、ruff 和 pytest 验证
- 03Python 反模式指南
- 04pytest fixture 与测试模式
- 05FastAPI 和 Django 说明
适用场景
- 01检查 Python 项目配置
- 02按统一顺序运行 Python 检查
- 03避免常见类型与异常错误
- 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