К основному содержанию
скилл CX Codex

gravitas-python — скилл для Claude Code: что делает и установка

Скилл gravitas-python добавляет к GRAVITAS проверки и шаблоны для Python. Он пригодится при ревью, настройке типов, линтинга и pytest.

MIT 419 установок ★ 509 обновлён 2026-10-24

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add udaysharmadev/Gravitas --skill gravitas-python -a claude-code
Открыть на GitHub

Что делает gravitas-python

gravitas-python расширяет базовый GRAVITAS правилами для Python-проектов. Скилл проверяет конфигурацию в pyproject.toml, setup.py, setup.cfg, файлах зависимостей и conftest.py, а также учитывает структуру пакета и type stubs. Без базового skills/gravitas/SKILL.md расширение не загрузится корректно.

Внутри есть цепочка проверки с mypy . --strict, ruff check ., ruff format --check . и pytest -v --tb=short. Скилл подсказывает, как искать причины ошибок типов, циклических импортов и отсутствующих stub-пакетов, предлагает паттерны фикстур и параметризованных тестов. Отдельные рекомендации даны для FastAPI и Django.

Какие задачи решает

  • проверить строгую типизацию Python-кода
  • найти ошибки линтинга и форматирования
  • собрать проверочную цепочку для pytest
  • разобрать циклический импорт или отсутствующий stub-пакет
  • подобрать паттерн теста для FastAPI или Django

Примеры запросов агенту

  • Проверь этот Python-проект по цепочке mypy, ruff и pytest.
  • Изучи pyproject.toml и объясни, какие настройки типов и линтинга действуют.
  • Разбери ошибку Optional[X] has no attribute Y и предложи исправление.

Как установить gravitas-python

1Через Skills CLI (Vercel)

npx skills add udaysharmadev/Gravitas --skill gravitas-python -a claude-code

2Вручную: положить файлы

~/.claude/skills/gravitas-python/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/gravitas-python/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о gravitas-python

Как установить gravitas-python в Claude Code?

Выполните npx skills add udaysharmadev/Gravitas --skill gravitas-python -a claude-code, затем проверьте файл ~/.claude/skills/gravitas-python/SKILL.md.

Что делает gravitas-python?

Скилл добавляет к GRAVITAS правила для Python: проверку типов через mypy или pyright, линтинг ruff или flake8, сценарии для pytest и разбор частых ошибок.

Нужно ли загружать базовый GRAVITAS?

Да. Сначала загрузите skills/gravitas/SKILL.md, затем gravitas-python, потому что это расширение базового скилла.

Исходный текст

SKILL.md · MIT
---
name: gravitas-python
description: >
  GRAVITAS extension for Python projects. Adds Python-specific recon,
  type checking with mypy/pyright, ruff/flake8 lint, pytest patterns,
  and common Python failure modes.
  Load in addition to the base GRAVITAS skill.
triggers:
  - "python"
  - "py"
  - "django"
  - "fastapi"
  - "flask"
  - "pytest"
  - "mypy"
---

# GRAVITAS — Python Extension

Extends the base GRAVITAS skill with Python-specific patterns.
Load `skills/gravitas/SKILL.md` first, then this file.

---

## Python Recon Additions

```
□ 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?
```

### Read pyproject.toml for type strictness
```bash
cat pyproject.toml | grep -A 10 "\[tool.mypy\]"
cat pyproject.toml | grep -A 10 "\[tool.ruff\]"
```

---

## Python Verification Chain

```bash
# 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-Specific Anti-Patterns

### Never use bare `except`
```python
BAD:  except:
GOOD: except ValueError as e:
GOOD: except (TypeError, ValueError) as e:
```

### Never shadow builtins
```python
BAD:  list = [1, 2, 3]     # shadows list()
BAD:  id = user.id         # shadows id()
GOOD: items = [1, 2, 3]
GOOD: user_id = user.id
```

### Type annotations required (with mypy strict)
```python
BAD:  def process(data):
GOOD: def process(data: dict[str, Any]) -> ProcessResult:
```

### Use dataclasses or Pydantic over dicts for structured data
```python
BAD:  return {"user_id": 1, "name": "Alice"}   # no type safety
GOOD: return UserResponse(user_id=1, name="Alice")
```

---

## Common Python Failure Modes

| Failure | Root Cause | Fix |
|---------|-----------|-----|
| `Optional[X] has no attribute Y` | None not handled | Add `if x is not None:` guard |
| `Incompatible return value type` | Wrong return type | Check function signature |
| `Missing return statement` | Not all paths return | Add explicit return |
| `Module has no attribute X` | Wrong import | Check module with `dir(module)` |
| `Cannot find implementation for X` | Missing stub | Install `types-X` package |
| Circular import | Import at module level | Move to function level or restructure |

---

## Test Patterns (pytest)

### Fixture pattern
```python
# 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
```

### Standard test structure
```python
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 for edge cases
```python
@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
```

---

## Framework-Specific Notes

### FastAPI
```python
# 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
```python
# 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
```

---

## Quick Reference

```bash
# 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
```

© udaysharmadev · MIT · udaysharmadev/Gravitas

Похожие скиллы

Все скиллы по теме «Языки программирования» →
python-pro qdhenry Субагент python-pro для Claude Code помогает рефакторить Python-код, оптимизировать его и добавлять сложные функции. Он подключается к таким задачам и пишет тесты вместе с изменениями. CX Codex ★ 1 357звёзд репо python alinaqi Задаёт правила разработки на Python: строгую типизацию с mypy, линтинг через ruff и тестирование на pytest с проверкой покрытия. CX Codex +1 282установок python-code-style Seth Hobson Скилл python-code-style для Claude Code задаёт правила стиля Python, линтеров, форматирования и документации для новых модулей, ревью и настройки проекта. CX Codex +1 16 456установок pare-python Dave-London MCP-сервер pare-python для Claude Code и Codex, который оборачивает ruff, mypy, pip, uv, black и pytest и возвращает их вывод типизированным JSON. Агент получает готовые данные вместо сырого текста терминала. CX Codex +1 ★ 141звёзд репо python-expert 0xfurai Субагент python-expert настраивает Claude Code на написание идиоматичного кода на Python по PEP 8, покрытие тестами через pytest и проверку типов с mypy. CX Codex ★ 1 029звёзд репо writing-python julianobarbosa Скилл writing-python держит агента в правилах Python 3.14+: сначала стандартная библиотека, аннотации типов у всех функций, uv и ruff вместо pip и black. CX Codex +1 134установок

Из того же набора4

Спонсоры проекта

Компании, которые помогают держать аналитику открытой