agentleFS
motola10motola10/claude-code-base/.claude/skills/python-standards/SKILL.md

python-standards

Skill1 starsChanged 5 months agoMITView on GitHub

Best-practice coding standards for Python code (manifests: pyproject.toml, requirements.txt). Referenced by the code-reviewer, qa-agent, and architect-agent when reviewing Python. Covers typing (mypy --strict), Ruff lint+format, uv, error handling, security, testing, packaging. FastAPI services ALSO load fastapi-standards on top of this. Do NOT use for JavaScript, TypeScript, Go, Java, or Rust.

  • Reads credentials

7 other projects use a version of this.

Adopted by

Most recently taken up by

The file

Show its rules and text

We split this skill into the rules it gives an agent

36 rules. 0 are common, 11 are distinctive, and 25 are very specific to this project.

  • 0

    Common

    Most of the 6 edited versions we read keep these.

  • 11

    Distinctive

    This author's own choices. Worth a look.

  • 25

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  • could be automatic: a setting could enforce it
  1. Very specific:

    Every rule has a stable ID like PY-ERR-3 (FRAMEWORK-AREA-NUMBER).

    line 39
  2. Distinctive:

    Target: all Python code — application services, data/ML pipelines, CLIs, libraries, automation.

    line 57
  3. Very specific:

    PY-BASE-3 (MUST): Use pyproject.toml as the single project manifest (PEP 621) — dependencies, build config, and tool config all live there.

    line 79
  4. Distinctive:

    PY-BASE-5 (MUST): All work happens in an isolated virtual environment — never install into the system interpreter.

    line 84
  5. Very specific:

    PY-STRUCT-1 (SHOULD): Use the src/ layout — package code under src/<package>/, tests under tests/.

    line 94
  6. Distinctive:

    PY-STRUCT-3 (MUST NOT): Create circular imports between modules.

    line 101
  7. Very specific:

    PY-STRUCT-4 (SHOULD): Keep modules cohesive and small.

    line 102
  8. Very specific:

    PY-STRUCT-5 (SHOULD): Use packages (__init__.py) deliberately — keep __init__.py thin (exports/metadata), not heavy logic.

    line 104
  9. Distinctive:

    PY-STYLE-2 (MUST): Follow PEP 8 (enforced by Ruff).

    line 114
  10. Very specific:

    PY-STYLE-5 (SHOULD): Keep functions small and single-purpose (soft guide: ≲ 40 lines, McCabe complexity ≲ 10).

    line 122
  11. Very specific:

    PY-STYLE-6 (SHOULD): Prefer explicit, readable constructs — comprehensions over manual loops where clearer, pathlib over os.path, f-strings …

    line 125
  12. Very specific:

    PY-STYLE-7 (MUST NOT): Leave dead code, commented-out blocks, or print() debugging in committed application code (see §8 for logging).

    line 128
  13. Distinctive:

    PY-TYPE-1 (MUST): All public functions, methods, and module-level constants are fully annotated (parameters and return types).

    line 135
  14. Very specific:

    PY-TYPE-2 (SHOULD): Run mypy in strict mode ([tool.mypy] strict = true) for new code.

    line 137
  15. Very specific:

    Treat type errors as build failures, not warnings.

    line 138
  16. Very specific:

    PY-TYPE-3 (SHOULD NOT): Use Any as an escape hatch, or add blanket # type: ignore.

    line 140
  17. Very specific:

    PY-TYPE-4 (SHOULD): Use modern typing syntax — X | None over Optional[X] (PEP 604), built-in generics (list[str], dict[str, int]), and from …

    line 142
  18. Very specific:

    PY-TYPE-5 (SHOULD): Prefer precise types over loose ones — Sequence/Mapping/Iterable for read-only params, concrete types for returns.

    line 145
  19. Distinctive:

    PY-ASYNC-2 (MUST): Don't mix paradigms incoherently — don't call blocking libraries from async paths, and don't create un-awaited …

    line 166
  20. Very specific:

    PY-ASYNC-3 (SHOULD): Run independent awaitables concurrently with asyncio.gather (or a TaskGroup, 3.11+), not sequentially, when they don't …

    line 169
  21. Very specific:

    PY-ERR-1 (MUST NOT): Use a bare except: or except Exception: that swallows errors.

    line 178
  22. Distinctive:

    PY-ERR-5 (MUST): Never leak internals (tracebacks, secrets, SQL) to end users/clients in production.

    line 186
  23. Very specific:

    PY-ERR-6 (SHOULD): Use try/finally or context managers to guarantee cleanup (files, locks, connections) on the error path.

    line 189
  24. Very specific:

    Use parameterized queries/an ORM.

    line 213
  25. Distinctive:

    PY-SEC-3 (MUST NOT): Commit secrets, API keys, tokens, or credentials.

    line 215
  26. Very specific:

    PY-SEC-4 (MUST NOT): Use eval, exec, or pickle/yaml.load/marshal on untrusted data.

    line 217
  27. Very specific:

    PY-SEC-5 (MUST): Use cryptographically safe primitives — secrets (not random) for tokens, a strong, slow password hash — Argon2 or bcrypt …

    line 219
  28. Very specific:

    PY-LOG-1 (MUST NOT): Use print() for application logging.

    line 232
  29. Very specific:

    PY-CONF-1 (MUST): Read configuration from the environment (12-factor), in one place.

    line 243
  30. Very specific:

    PY-TEST-3 (SHOULD): Follow the test pyramid (many unit, fewer integration, few e2e) and the Arrange–Act–Assert shape.

    line 259
  31. Very specific:

    PY-TEST-6 (MUST): Test error paths and edge cases (pytest.raises(...)), not just the happy path — especially validation and the operational …

    line 267
  32. Distinctive:

    PY-DEP-1 (SHOULD): Add a dependency only when it earns its place — prefer the standard library and small, maintained packages over large …

    line 274
  33. Very specific:

    PY-DOC-1 (MUST): Every repo has a README covering purpose, prerequisites, setup, run, test, and configuration — runnable from the README …

    line 286
  34. Distinctive:

    PY-DOC-2 (SHOULD): Write docstrings (PEP 257) for public modules, classes, and functions with non-obvious contracts — document parameters, …

    line 288
  35. Very specific:

    PY-DOC-3 (SHOULD): Use the Google docstring style consistently (Args: / Returns: / Raises: sections).

    line 291
  36. Distinctive:

    All review questions settled — recorded here as the decision log for this standard:

    line 298

“Common” is measured: kept by at least 6 in 10 of the 6 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Python Coding Standard (v1.0 — LOCKED)

Status: ✅ Locked — all review questions resolved (decision log at end of doc). Built from the Node.js reference template (codebase-standards/nodejs.md v1.0) — same constraint language, rule-ID format, severity mapping, and lean depth. This is the agnostic Python core: it governs all Python — scripts, data/ML jobs, CLIs, libraries, and web services. Web frameworks layer on top: FastAPI is a separate overlay (codebase-standards/fastapi.md, to come) that builds on this core, the way Next.js builds on React. Amendable later via the normal process — add new rule IDs, never renumber.

On adoption this becomes .claude/skills/python-standards/SKILL.md + references/*.md.

Toolchain verified current as of 2026-06-12 (via Context7 + PyPI): CPython non-EOL line is 3.10 – 3.14 (latest 3.14.x); Ruff 0.15.x; uv 0.11.x; mypy 2.1.x; pydantic 2.13.x with pydantic-settings 2.14.x (separate package); pip-audit 2.10.x; pwdlib 0.3.x; argon2-cffi 25.x. Rules below are written version-agnostically; these are reference points, not pins.


How to read this document

Constraint language (RFC 2119)

  • MUST / MUST NOT — hard requirement. A violation is a blocking issue.
  • SHOULD / SHOULD NOT — strong recommendation. Deviation is allowed only with a written, in-code justification (a # Justification: comment or PR note).
  • MAY — optional; a legitimate choice with no penalty either way.

Rule IDs

Every rule has a stable ID like PY-ERR-3 (FRAMEWORK-AREA-NUMBER). The Code Reviewer agent MUST cite the rule ID in its findings so each comment is auditable and traceable to this document. IDs are stable — never renumber; add new ones with the next free number.

Severity mapping (how a violation surfaces in a review)

This document says…Reviewer severityGate
MUST/MUST NOT in SecurityCriticalBlocks merge
MUST/MUST NOT elsewhereCritical / Warning (by impact)Blocks merge if it risks correctness or data loss
SHOULD without justificationWarningShould fix
MAY / stylistic preferenceSuggestionNice to have

Scope & Assumptions (stated explicitly)

If any is wrong for your context, flag it — it changes the rules below.

  1. Target: all Python code — application services, data/ML pipelines, CLIs, libraries, automation.
  2. Runtime: a supported, non-EOL CPython, with a minimum floor of 3.12 (pinned via requires-python = ">=3.12"). CPython supports each minor for ~5 years; track the cycle and don't ship on EOL versions.
  3. Typing: new code is fully type-annotated and checked by mypy in strict mode in CI. Python is used as a typed language here, not dynamically. (pyright is an acceptable per-project alternative for VS Code-centric teams, but mypy --strict is the standard default.)
  4. Tooling baseline: Ruff (lint + format), mypy --strict (types), pytest (tests), and uv for dependency/lockfile/venv management. All config lives in pyproject.toml.
  5. Web frameworks are out of scope here. FastAPI/Django/Flask rules live in their own overlay standards that build on this core.
  6. Custom overrides: anything in the project's custom-standards skill overrides this document.

1. Runtime, Tooling & Project Baseline

  • PY-BASE-1 (MUST): Declare the supported Python version in pyproject.toml requires-python = ">=3.12" (the standard floor) and pin the dev version with uv (uv python pin, producing .python-version). CI MUST run on the pinned version(s).
  • PY-BASE-2 (MUST NOT): Target or run on an EOL Python. Track the release cycle and plan upgrades before end-of-life.
  • PY-BASE-3 (MUST): Use pyproject.toml as the single project manifest (PEP 621) — dependencies, build config, and tool config all live there. MUST NOT rely on a bare setup.py or loose requirements.txt as the source of truth for a new project.
  • PY-BASE-4 (MUST): Manage dependencies with uv and commit its uv.lock; CI installs from the lockfile (uv sync --frozen) for reproducible builds.
  • PY-BASE-5 (MUST): All work happens in an isolated virtual environment — never install into the system interpreter. The env is reproducible from the lockfile alone.
  • PY-BASE-6 (MUST): Provide standard project commands (via pyproject.toml scripts, a Makefile, or uv/tox): at least lint, format-check, type-check, and test. A new contributor runs the project from these alone.

2. Project Structure & Architecture

  • PY-STRUCT-1 (SHOULD): Use the src/ layout — package code under src/<package>/, tests under tests/. This prevents accidental imports of un-installed local code and matches packaging best practice.
  • PY-STRUCT-2 (SHOULD): Organize by feature/domain, not by technical type. For services, respect layering and dependency direction: interface/transport → service (business logic) → data access. Business logic MUST NOT depend on transport (HTTP/CLI) details; data access is isolated behind a repository/gateway.
  • PY-STRUCT-3 (MUST NOT): Create circular imports between modules. The reviewer flags any cycle.
  • PY-STRUCT-4 (SHOULD): Keep modules cohesive and small; prefer explicit, absolute imports over wildcard (from x import *) imports, which are forbidden in application code.
  • PY-STRUCT-5 (SHOULD): Use packages (__init__.py) deliberately — keep __init__.py thin (exports/metadata), not heavy logic.

3. Code Style & Conventions

  • PY-STYLE-1 (MUST): Style is enforced by tooling, not reviewer opinion. The repo MUST run ruff format (formatting) and ruff check (linting) — Ruff replaces Black, isort, and Flake8 — and both MUST pass in CI. Formatting comments in review are out of scope.
  • PY-STYLE-2 (MUST): Follow PEP 8 (enforced by Ruff). Default line length is the formatter's (88); keep it consistent project-wide.
  • PY-STYLE-3 (SHOULD): Enable a sensible Ruff ruleset beyond defaults under [tool.ruff.lint] in pyproject.toml — at least E/F (pycodestyle/Pyflakes), I (isort), B (bugbear), UP (pyupgrade), SIM (simplify), and S (flake8-bandit security). Note: Ruff does not enable S or C901 by default, so they must be listed explicitly in select.
  • PY-STYLE-4 (MUST): Naming — snake_case for variables/functions/modules, PascalCase for classes, UPPER_SNAKE_CASE for constants, leading underscore _private for internal names.
  • PY-STYLE-5 (SHOULD): Keep functions small and single-purpose (soft guide: ≲ 40 lines, McCabe complexity ≲ 10). Enforce by selecting Ruff's C901 and setting [tool.ruff.lint.mccabe] max-complexity = 10. Long/complex functions are a refactor signal.
  • PY-STYLE-6 (SHOULD): Prefer explicit, readable constructs — comprehensions over manual loops where clearer, pathlib over os.path, f-strings over %/.format(), context managers (with) for resource handling.
  • PY-STYLE-7 (MUST NOT): Leave dead code, commented-out blocks, or print() debugging in committed application code (see §8 for logging).

4. Type Hints

  • PY-TYPE-1 (MUST): All public functions, methods, and module-level constants are fully annotated (parameters and return types). mypy MUST run in CI and pass.
  • PY-TYPE-2 (SHOULD): Run mypy in strict mode ([tool.mypy] strict = true) for new code. Treat type errors as build failures, not warnings. (pyright is an acceptable per-project substitute, but mypy --strict is the default.)
  • PY-TYPE-3 (SHOULD NOT): Use Any as an escape hatch, or add blanket # type: ignore. Each suppression MUST be narrow and carry a reason (# type: ignore[code] # why).
  • PY-TYPE-4 (SHOULD): Use modern typing syntax — X | None over Optional[X] (PEP 604), built-in generics (list[str], dict[str, int]), and from __future__ import annotations where forward refs help. Use TypeAlias/TypedDict/Protocol for complex shapes.
  • PY-TYPE-5 (SHOULD): Prefer precise types over loose ones — Sequence/Mapping/Iterable for read-only params, concrete types for returns. Avoid bare dict/list where a TypedDict/dataclass expresses intent.
# ❌ Untyped, loose
def get_user(id):
    ...

# ✅ Fully typed, modern syntax
def get_user(user_id: int) -> User | None:
    ...

5. Asynchronous & Concurrency Patterns

  • PY-ASYNC-1 (MUST): In async code, never block the event loop — no synchronous I/O, time.sleep, or CPU-heavy work inside async def. Use await for I/O; offload CPU-bound work to a process pool, and blocking calls to asyncio.to_thread/an executor.
  • PY-ASYNC-2 (MUST): Don't mix paradigms incoherently — don't call blocking libraries from async paths, and don't create un-awaited coroutines (a coroutine that's never awaited is a bug the reviewer flags).
  • PY-ASYNC-3 (SHOULD): Run independent awaitables concurrently with asyncio.gather (or a TaskGroup, 3.11+), not sequentially, when they don't depend on each other.
  • PY-ASYNC-4 (SHOULD): Choose concurrency to fit the workload — asyncio for I/O-bound, multiprocessing/process pools for CPU-bound. Don't reach for threads to speed up CPU-bound work.

6. Error Handling

  • PY-ERR-1 (MUST NOT): Use a bare except: or except Exception: that swallows errors. Catch the most specific exception you can handle; let everything else propagate.
  • PY-ERR-2 (MUST NOT): Silently pass on exceptions (except ...: pass) — if you catch, you handle, re-raise, or meaningfully degrade, with a comment explaining why.
  • PY-ERR-3 (MUST): Raise specific, typed exceptions. Define domain exceptions inheriting from a project base (e.g. class AppError(Exception)); MUST NOT raise Exception("...") generically.
  • PY-ERR-4 (SHOULD): Preserve context — use raise NewError(...) from err when re-raising, and include actionable detail in the message. Don't discard the original traceback.
  • PY-ERR-5 (MUST): Never leak internals (tracebacks, secrets, SQL) to end users/clients in production; log full detail server-side and surface a safe message. (Web overlays specify the HTTP shape.)
  • PY-ERR-6 (SHOULD): Use try/finally or context managers to guarantee cleanup (files, locks, connections) on the error path.
# ❌ Swallows everything, hides bugs
try:
    user = repo.get(user_id)
except:                       # PY-ERR-1
    user = None               # PY-ERR-2

# ✅ Specific, contextual
try:
    user = repo.get(user_id)
except UserNotFoundError as err:
    raise AppError(f"User {user_id} unavailable") from err   # PY-ERR-3 / PY-ERR-4

7. Security (violations here are Critical / blocking)

  • PY-SEC-1 (MUST): Validate and parse all external input at the boundary with a schema/typed model (e.g. pydantic) — don't trust raw dicts/strings from requests, files, env, or CLI.
  • PY-SEC-2 (MUST NOT): Build SQL/queries or shell commands by string formatting with user input. Use parameterized queries/an ORM; for subprocess use an args list with shell=False, never os.system or shell=True with interpolated input.
  • PY-SEC-3 (MUST NOT): Commit secrets, API keys, tokens, or credentials. Secrets come from the environment/secret manager only (§9). Any hardcoded secret is a blocking finding.
  • PY-SEC-4 (MUST NOT): Use eval, exec, or pickle/yaml.load/marshal on untrusted data. Use yaml.safe_load, json, or a safe schema instead.
  • PY-SEC-5 (MUST): Use cryptographically safe primitives — secrets (not random) for tokens, a strong, slow password hash — Argon2 or bcrypt via a maintained library (argon2-cffi, bcrypt, or pwdlib); avoid the long-unmaintained passlib (last release 2020). Never MD5, SHA-1, or a plain unsalted hash for passwords.
  • PY-SEC-6 (MUST): Audit dependencies for known vulnerabilities in CI (pip-audit or equivalent); fail on high/critical advisories that have a fix. Enable Ruff's S (bandit) rules for static checks.
  • PY-SEC-7 (SHOULD): Apply least privilege — the process, DB user, and file/network access have only what they need.

8. Logging & Observability

  • PY-LOG-1 (MUST NOT): Use print() for application logging. Use the logging module (or structlog).
  • PY-LOG-2 (MUST): Log with levels and structure (prefer JSON/structured in production), include correlation context, and MUST NOT log secrets, passwords, tokens, or full PII.
  • PY-LOG-3 (SHOULD): Configure logging once at the app entry point; libraries get a module logger via logging.getLogger(__name__) and never configure handlers themselves.

9. Configuration & Secrets

  • PY-CONF-1 (MUST): Read configuration from the environment (12-factor), in one place; the rest of the app imports a typed, validated settings object (e.g. pydantic-settings).
  • PY-CONF-2 (MUST): Validate config at startup and fail fast (non-zero exit) on missing/invalid required values — never discover a missing var mid-request.
  • PY-CONF-3 (MUST): Provide a committed .env.example (no real values); real .env files are git-ignored. Production secrets come from the platform/secret manager.

10. Testing

  • PY-TEST-1 (MUST): New or changed behavior ships with tests (pytest). Changed logic with no corresponding test is treated as insufficient coverage.
  • PY-TEST-2 (MUST): Tests are deterministic and isolated — mock external network/services in unit tests, no order dependency, no shared mutable state. Use pytest fixtures for setup, not ad-hoc globals.
  • PY-TEST-3 (SHOULD): Follow the test pyramid (many unit, fewer integration, few e2e) and the Arrange–Act–Assert shape. Name tests by behavior: test_get_user_returns_none_when_missing.
  • PY-TEST-4 (SHOULD): Target ≥ 80% coverage on changed code (not whole-repo) via pytest-cov. Coverage is a floor, not the goal; don't chase it on trivial code or test library internals.
  • PY-TEST-5 (MUST): Tests MUST make meaningful assertions. A test that runs code but asserts nothing (or only "doesn't raise") inflates coverage without verifying behavior — the reviewer/QA agent flags such weak/assertion-free tests, even when the 80% bar is met.
  • PY-TEST-6 (MUST): Test error paths and edge cases (pytest.raises(...)), not just the happy path — especially validation and the operational exceptions from §6.

11. Dependencies & Supply Chain

  • PY-DEP-1 (SHOULD): Add a dependency only when it earns its place — prefer the standard library and small, maintained packages over large transitive trees.
  • PY-DEP-2 (MUST): Separate runtime deps from dev/test/tooling deps (dependency groups / extras). Build- and test-only tools MUST NOT ship as runtime dependencies.
  • PY-DEP-3 (MUST): Pin via lockfile (PY-BASE-4) and keep dependencies current via a managed process (e.g. Renovate/Dependabot), not ad-hoc bumps.
  • PY-DEP-4 (SHOULD NOT): Introduce unmaintained, deprecated, or known-vulnerable packages.

12. Documentation

  • PY-DOC-1 (MUST): Every repo has a README covering purpose, prerequisites, setup, run, test, and configuration — runnable from the README alone.
  • PY-DOC-2 (SHOULD): Write docstrings (PEP 257) for public modules, classes, and functions with non-obvious contracts — document parameters, returns, and raised exceptions. Document the why in comments, not the what.
  • PY-DOC-3 (SHOULD): Use the Google docstring style consistently (Args: / Returns: / Raises: sections). The reviewer flags mixed styles within a project.

Resolved Decisions

All review questions settled — recorded here as the decision log for this standard:

#QuestionDecision
Q1Python version floor✅ >=3.12 (Assumption #2 / PY-BASE-1).
Q2Type checker✅ mypy in strict mode (Assumption #3 / PY-TYPE-1/2). pyright is an acceptable per-project alternative; mypy --strict is the default. Grounded in adoption signals: mypy ~161M PyPI downloads/mo vs pyright ~34M, and is the reference checker for the typing PEPs.
Q3Dependency / packaging tool✅ uv — manages deps, uv.lock, venv, and Python version (PY-BASE-1/4).
Q4Docstring style✅ Google style (Args:/Returns:/Raises:), used consistently (PY-DOC-3).
Q5Node-template adjustments✅ None — keep the structure consistent across all nine standards.

Inherited from the locked Node template (Node Q3/Q4/Q5/Q6): MUST/SHOULD/MAY altitude, ≥80% changed-code coverage + flag weak tests, FRAMEWORK-AREA-N rule IDs + severity mapping, and lean depth.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.