tech-stack-python

Python stack context for workflow skills — pytest, mypy and ruff commands, SQLAlchemy and Alembic guidance, FastAPI, Django and Flask patterns, and reference file paths.

SKILL.md

GitHub

Tech Stack: Python

Overview

Python context for the workflow skills and review agents: commands, detection markers, the data-layer rules that bite, settings and scan recipes. Generic FastAPI/Django/SQLAlchemy practice is assumed, not restated.

When To Use

Loaded automatically when the active tech stack is python; never invoked directly.

Build & Test Commands

No compile step: type checking and tests are the verification gates.

  • Type check (compile-equivalent): mypy . or pyright (whichever the project uses)
  • Test (batch): pytest -q --tb=short <path/to/module> or pytest -q --tb=short -k <pattern>
  • Test (full): pytest -q --tb=short
  • Bounded output is the default. Batch checkpoints run these through bash scripts/mtk-verify-run.sh --label <batch-id>-<step> -- <cmd> — the wrapper's bounded tail is the evidence, the log path is the receipt.
  • Format: see ## Format Command.
  • Lint: ruff check <path> (or flake8 / pylint per project)

Prefer project targets when present: tox, poetry run pytest, make test, just test.

File Extensions & Markers

How setup-bootstrap detects this stack in a repository:

Marker Confidence
pyproject.toml High
setup.py or setup.cfg High
requirements.txt Medium
Pipfile or poetry.lock High
.python-version Low (supplemental)

Detection command:

find . -maxdepth 2 \( -name "pyproject.toml" -o -name "setup.py" -o -name "requirements.txt" -o -name "Pipfile" \) 2>/dev/null | head -3

ORM & Data Layer Guidance

  • SQLite in-memory does not validate Postgres behavior (JSONB, arrays, ILIKE, full-text search, advisory locks). Use testcontainers-python or a real test database when database semantics matter; for Django, pytest-django against Postgres.
  • A sync DB driver (or requests) inside an async def endpoint blocks the event loop. Use a sync endpoint over a sync driver; do not fake async.
  • Review Alembic autogenerated migrations before applying: it guesses, and reads a rename as drop + add.
  • Schema changes ship expand-then-contract (.claude/references/schema-migrations.md): no drop, rename, type narrowing or NOT NULL on existing rows in the same deploy as code that still uses the old shape. Run every down path before merging: alembic downgrade <revision before the PR's first migration>; Django migrate <app> <previous>, with reverse_code on every RunPython (RunPython.noop when there is nothing to undo).
  • Writes run inside an explicit transaction (with session.begin():, transaction.atomic()), one commit per request or handler; audited writes follow domain-finance.md.

Framework Patterns

Match the project's existing FastAPI, Django or Flask conventions. Two boundaries reviewers check: request and response shapes are validated models (Pydantic, DRF serializers, Django forms), never raw dict / request.POST in business logic; and side effects (email, queue, external calls) are explicit in the service layer, not buried in a model or serializer.

Test Level Guidance

Endpoints, persistence, auth and serialization get integration tests (TestClient, Django Client / DRF APIClient); pure logic gets unit tests with parametrize. Frameworks, fixtures, mocking and the test database: .claude/references/python/testing-supplement.md.

Coding Style Reference

Path: .claude/references/python/coding-guidelines.md — a placeholder (status: placeholder, not shipped by bootstrap) until the team writes real guidelines. Until then: PEP 8 via ruff format, type hints on public functions, no import *.

Analyzer Configuration

.claude/references/python/analyzer-config.md carries the ruff rule set and mypy strict settings. Lint with analyzer capture:

ruff check --output-format json . | bash "${CLAUDE_PLUGIN_ROOT}/hooks/parse-build-diagnostics.sh" --format ruff > .mtk/analyzer-output.json

Recommended Tooling

docs/recommended-tooling/python.md (with docs/recommended-tooling/shared.md): context7, Pyright/basedpyright LSP, Ruff LSP. setup-bootstrap prints both; install is manual.

Reference Files

Loaded by commands and review agents when the active stack is python:

  • .claude/references/python/coding-guidelines.md — Python style guide (placeholder until written)
  • .claude/references/python/testing-supplement.md — pytest, fixtures, mocking, test database
  • .claude/references/python/analyzer-config.md — ruff rules and mypy strict settings
  • docs/recommended-tooling/python.md — recommended MCPs, plugins and editor integrations

The data-layer rules live in this skill (## ORM & Data Layer Guidance).

Settings Additions

setup-bootstrap merges these, after .claude/references/settings-baseline.md, into the project's permissions.allow / permissions.deny (never an allowedTools key).

allow (merge: union)

  • Bash(python:*)
  • Bash(python3:*)
  • Bash(pytest:*)
  • Bash(mypy:*)
  • Bash(ruff:*)
  • Bash(black:*)
  • Bash(poetry:*)
  • Bash(pip:*)
  • Bash(tox:*)

deny (merge: union)

  • Read(**/.env.production)
  • Read(**/secrets.yaml)

hooks (do NOT add)

format-on-edit.sh is wired by the plugin's own hooks/hooks.json. Bootstrap never copies an MTK hook into the target's settings.json; setup-bootstrap Settings Merge says why. Formatting runs at Stop, not PostToolUse, which matters most here: ruff check --fix rewrites imports and bindings, so a mid-turn run would change what a file means between the read and the next edit.

Format Command

ruff format <file> && ruff check --fix <file>   # or black <file>

At flush the hook picks ruff → black based on what's installed, once per edited file (deduped, with files deleted during the turn dropped). Failures log to stderr but never block the edit.

Pre-Commit Review Items

Tool-keyed items for the generated pre-commit-review-list.md; setup-bootstrap keeps those whose tool the scan detected.

  • [SQLAlchemy] session management, eager/lazy loading, N+1 patterns
  • [FastAPI] dependency injection, Pydantic validation
  • [Django] select_related/prefetch_related, transaction.atomic

Scan Recipes

Used by setup-audit when auditing a Python repository.

Dependency Registry Verification

Before planning the install of any PyPI package not already in requirements.txt / pyproject.toml, verify it exists and is the real one (criterion 0 of .claude/references/dependency-intake-checklist.md). Not found, or a typosquat-like name, is an immediate block; an unverified AI-recommended package is tagged [ASSUMED] with a checkpoint:human-verify step before any install.

pip index versions <pkg>

Project Structure

find . -maxdepth 2 \( -name "pyproject.toml" -o -name "setup.py" -o -name "setup.cfg" -o -name "requirements*.txt" -o -name "Pipfile" -o -name "poetry.lock" \) 2>/dev/null
cat .python-version 2>/dev/null; grep -E "python_requires|python =" pyproject.toml setup.py setup.cfg 2>/dev/null | head -5
find . -maxdepth 3 -name "__init__.py" -not -path "*/.venv/*" -not -path "*/venv/*" -not -path "*/site-packages/*" | head -20

Patterns In Use

grep -rlE "from (fastapi|django|flask)|import (fastapi|flask)" --include="*.py" | head -10
grep -rlE "from sqlalchemy|sqlalchemy\.orm|models\.Model" --include="*.py" | head -10
grep -rlE "from pydantic|BaseModel|marshmallow" --include="*.py" | head -10
grep -rl "async def" --include="*.py" | head -10
find . \( -name "mypy.ini" -o -name "pyrightconfig.json" \) 2>/dev/null; grep -E "mypy|pyright" pyproject.toml setup.cfg 2>/dev/null | head -5

Data Layer

grep -rlE "DeclarativeBase|declarative_base|Mapped\[|session\.(execute|query)" --include="*.py" | head -5
find . -name "alembic.ini" 2>/dev/null; find . -path "*/migrations/*" -name "*.py" -not -path "*/.venv/*" | head -10
grep -rlE "select_related|prefetch_related|transaction\.atomic" --include="*.py" | head -5
grep -rnE "lazy=|create_engine|sessionmaker|SessionLocal" --include="*.py" | head -5

Infrastructure

grep -rlE "import boto3|from boto3|def lambda_handler" --include="*.py" | head -10
find . \( -name "Dockerfile" -o -name "docker-compose*" -o -name "*.tf" -o -name "serverless.yml" -o -name "cdk.json" \) 2>/dev/null | head -10
grep -rlE "celery|kafka|rabbitmq|redis|secretsmanager|hvac" --include="*.py" | head -10

Naming Conventions

find . \( -name "*router*.py" -o -name "*views*.py" -o -name "*handler*.py" -o -name "models.py" \) -not -path "*/.venv/*" -not -path "*test*" | head -15

Testing Patterns

grep -rh "pytest\|tox" pyproject.toml setup.cfg requirements*.txt 2>/dev/null | sort -u
find . -name "conftest.py" -not -path "*/.venv/*" | head -10
grep -rlE "unittest\.mock|pytest_mock|monkeypatch|factory_boy|testcontainers|pytest-django|pytest-postgresql" --include="*.py" | head -10

Configuration

grep -rlE "pydantic_settings|BaseSettings|os\.environ\.get" --include="*.py" | head -10
find . \( -name "settings.py" -o -name "config.py" -o -name ".env.example" \) -not -path "*/.venv/*" | head -10
grep -rlE "getLogger|loguru|structlog" --include="*.py" | head -10

Verification

  • Tech stack skill is loaded when .claude/tech-stack contains python
  • Build (type check) and test commands execute correctly for the target project
  • Reference files exist at the paths listed in ## Reference Files
  • Scan recipes produce meaningful output for a Python repository