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
- takayoshitoyoda05/claude-ml-templatetheir own version, first seen Oct 20, 2026
- pablolok/claude-skillstheir own version, first seen Oct 13, 2026
- microsoft/amplifier-module-tool-skillstheir own version, first seen Oct 13, 2026
- microsoft/amplifier-bundle-skillstheir own version, first seen Oct 13, 2026
- L-1124/QQMusicApitheir own version, first seen Oct 8, 2026
- alphacrack/readme2demotheir own version, first seen Jul 5, 2026
Other versions7 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 7
- L-1124/QQMusicApi★ 529same name
- microsoft/amplifier-bundle-skills★ 12same name
- alphacrack/readme2demo★ 9same name
- microsoft/amplifier-module-tool-skills★ 8same name
- rishapgandhi/python-skills★ 4same name
- pablolok/claude-skills★ 1same name
- takayoshitoyoda05/claude-ml-template★ 1same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository19 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- custom-standardsSkill
- agent-code-to-confirmSkill
- agent-to-confirmSkill
- claude-guideline-creationSkill
- skill-creatorSkill
- youtube-to-guidelineSkill
- youtube-transcribeSkill
- fastapi-standardsSkill
- general-standardsSkill
- go-standardsSkill
- java-standardsSkill
- nextjs-standardsSkill
- nodejs-standardsSkill
- react-standardsSkill
- reviewing-codebasesSkill
- rust-standardsSkill
- skill-toggleSkill
- typescript-standardsSkill
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
- Very specific: line 39
Every rule has a stable ID like PY-ERR-3 (FRAMEWORK-AREA-NUMBER).
- Distinctive: line 57
Target: all Python code — application services, data/ML pipelines, CLIs, libraries, automation.
- Very specific: line 79
PY-BASE-3 (MUST): Use pyproject.toml as the single project manifest (PEP 621) — dependencies, build config, and tool config all live there.
- Distinctive: line 84
PY-BASE-5 (MUST): All work happens in an isolated virtual environment — never install into the system interpreter.
- Very specific: line 94
PY-STRUCT-1 (SHOULD): Use the src/ layout — package code under src/<package>/, tests under tests/.
- Distinctive: line 101
PY-STRUCT-3 (MUST NOT): Create circular imports between modules.
- Very specific: line 102
PY-STRUCT-4 (SHOULD): Keep modules cohesive and small.
- Very specific: line 104
PY-STRUCT-5 (SHOULD): Use packages (__init__.py) deliberately — keep __init__.py thin (exports/metadata), not heavy logic.
- Distinctive: line 114
PY-STYLE-2 (MUST): Follow PEP 8 (enforced by Ruff).
- Very specific: line 122
PY-STYLE-5 (SHOULD): Keep functions small and single-purpose (soft guide: ≲ 40 lines, McCabe complexity ≲ 10).
- Very specific: line 125
PY-STYLE-6 (SHOULD): Prefer explicit, readable constructs — comprehensions over manual loops where clearer, pathlib over os.path, f-strings …
- Very specific: line 128
PY-STYLE-7 (MUST NOT): Leave dead code, commented-out blocks, or print() debugging in committed application code (see §8 for logging).
- Distinctive: line 135
PY-TYPE-1 (MUST): All public functions, methods, and module-level constants are fully annotated (parameters and return types).
- Very specific: line 137
PY-TYPE-2 (SHOULD): Run mypy in strict mode ([tool.mypy] strict = true) for new code.
- Very specific: line 138
Treat type errors as build failures, not warnings.
- Very specific: line 140
PY-TYPE-3 (SHOULD NOT): Use Any as an escape hatch, or add blanket # type: ignore.
- Very specific: line 142
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 …
- Very specific: line 145
PY-TYPE-5 (SHOULD): Prefer precise types over loose ones — Sequence/Mapping/Iterable for read-only params, concrete types for returns.
- Distinctive: line 166
PY-ASYNC-2 (MUST): Don't mix paradigms incoherently — don't call blocking libraries from async paths, and don't create un-awaited …
- Very specific: line 169
PY-ASYNC-3 (SHOULD): Run independent awaitables concurrently with asyncio.gather (or a TaskGroup, 3.11+), not sequentially, when they don't …
- Very specific: line 178
PY-ERR-1 (MUST NOT): Use a bare except: or except Exception: that swallows errors.
- Distinctive: line 186
PY-ERR-5 (MUST): Never leak internals (tracebacks, secrets, SQL) to end users/clients in production.
- Very specific: line 189
PY-ERR-6 (SHOULD): Use try/finally or context managers to guarantee cleanup (files, locks, connections) on the error path.
- Very specific: line 213
Use parameterized queries/an ORM.
- Distinctive: line 215
PY-SEC-3 (MUST NOT): Commit secrets, API keys, tokens, or credentials.
- Very specific: line 217
PY-SEC-4 (MUST NOT): Use eval, exec, or pickle/yaml.load/marshal on untrusted data.
- Very specific: line 219
PY-SEC-5 (MUST): Use cryptographically safe primitives — secrets (not random) for tokens, a strong, slow password hash — Argon2 or bcrypt …
- Very specific: line 232
PY-LOG-1 (MUST NOT): Use print() for application logging.
- Very specific: line 243
PY-CONF-1 (MUST): Read configuration from the environment (12-factor), in one place.
- Very specific: line 259
PY-TEST-3 (SHOULD): Follow the test pyramid (many unit, fewer integration, few e2e) and the Arrange–Act–Assert shape.
- Very specific: line 267
PY-TEST-6 (MUST): Test error paths and edge cases (pytest.raises(...)), not just the happy path — especially validation and the operational …
- Distinctive: line 274
PY-DEP-1 (SHOULD): Add a dependency only when it earns its place — prefer the standard library and small, maintained packages over large …
- Very specific: line 286
PY-DOC-1 (MUST): Every repo has a README covering purpose, prerequisites, setup, run, test, and configuration — runnable from the README …
- Distinctive: line 288
PY-DOC-2 (SHOULD): Write docstrings (PEP 257) for public modules, classes, and functions with non-obvious contracts — document parameters, …
- Very specific: line 291
PY-DOC-3 (SHOULD): Use the Google docstring style consistently (Args: / Returns: / Raises: sections).
- Distinctive: line 298
All review questions settled — recorded here as the decision log for this standard:
“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.
Files
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.mdv1.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-settings2.14.x (separate package);pip-audit2.10.x;pwdlib0.3.x;argon2-cffi25.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 severity | Gate |
MUST/MUST NOT in Security | Critical | Blocks merge |
MUST/MUST NOT elsewhere | Critical / Warning (by impact) | Blocks merge if it risks correctness or data loss |
SHOULD without justification | Warning | Should fix |
MAY / stylistic preference | Suggestion | Nice to have |
Scope & Assumptions (stated explicitly)
If any is wrong for your context, flag it — it changes the rules below.
- Target: all Python code — application services, data/ML pipelines, CLIs, libraries, automation.
- 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. - 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.)
- Tooling baseline: Ruff (lint + format), mypy --strict (types), pytest (tests), and
uv for dependency/lockfile/venv management. All config lives in
pyproject.toml. - Web frameworks are out of scope here. FastAPI/Django/Flask rules live in their own overlay standards that build on this core.
- Custom overrides: anything in the project's
custom-standardsskill overrides this document.
1. Runtime, Tooling & Project Baseline
- PY-BASE-1 (MUST): Declare the supported Python version in
pyproject.tomlrequires-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.tomlas the single project manifest (PEP 621) — dependencies, build config, and tool config all live there. MUST NOT rely on a baresetup.pyor looserequirements.txtas 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.tomlscripts, aMakefile, oruv/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 undersrc/<package>/, tests undertests/. 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__.pythin (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) andruff 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]inpyproject.toml— at leastE/F(pycodestyle/Pyflakes),I(isort),B(bugbear),UP(pyupgrade),SIM(simplify), andS(flake8-bandit security). Note: Ruff does not enableSorC901by default, so they must be listed explicitly inselect. - PY-STYLE-4 (MUST): Naming —
snake_casefor variables/functions/modules,PascalCasefor classes,UPPER_SNAKE_CASEfor constants, leading underscore_privatefor internal names. - PY-STYLE-5 (SHOULD): Keep functions small and single-purpose (soft guide: ≲ 40 lines, McCabe
complexity ≲ 10). Enforce by selecting Ruff's
C901and 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,
pathliboveros.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
Anyas 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 | NoneoverOptional[X](PEP 604), built-in generics (list[str],dict[str, int]), andfrom __future__ import annotationswhere forward refs help. UseTypeAlias/TypedDict/Protocolfor complex shapes. - PY-TYPE-5 (SHOULD): Prefer precise types over loose ones —
Sequence/Mapping/Iterablefor read-only params, concrete types for returns. Avoid baredict/listwhere aTypedDict/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 insideasync def. Useawaitfor I/O; offload CPU-bound work to a process pool, and blocking calls toasyncio.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 aTaskGroup, 3.11+), not sequentially, when they don't depend on each other. - PY-ASYNC-4 (SHOULD): Choose concurrency to fit the workload —
asynciofor 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:orexcept 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 NOTraise Exception("...")generically. - PY-ERR-4 (SHOULD): Preserve context — use
raise NewError(...) from errwhen 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/finallyor 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-47. 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, neveros.systemorshell=Truewith 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, orpickle/yaml.load/marshalon untrusted data. Useyaml.safe_load,json, or a safe schema instead. - PY-SEC-5 (MUST): Use cryptographically safe primitives —
secrets(notrandom) for tokens, a strong, slow password hash — Argon2 or bcrypt via a maintained library (argon2-cffi,bcrypt, orpwdlib); avoid the long-unmaintainedpasslib(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-auditor equivalent); fail on high/critical advisories that have a fix. Enable Ruff'sS(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 theloggingmodule (orstructlog). - 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.envfiles 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
pytestfixtures 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
READMEcovering 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:
| # | Question | Decision |
| Q1 | Python version floor | ✅ >=3.12 (Assumption #2 / PY-BASE-1). |
| Q2 | Type 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. |
| Q3 | Dependency / packaging tool | ✅ uv — manages deps, uv.lock, venv, and Python version (PY-BASE-1/4). |
| Q4 | Docstring style | ✅ Google style (Args:/Returns:/Raises:), used consistently (PY-DOC-3). |
| Q5 | Node-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.
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
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.

