Python

Python services and tooling.

Python services and tooling. The BLOCKER tier is mostly injection and safety footguns Python makes easy to write by accident — mutable default arguments, bare except clauses, SQL built by string interpolation, shell=True subprocess calls, blocking I/O inside async def. The HIGH tier pushes toward a typed, timezone-aware, resource-safe style: type hints on new public functions, context managers instead of manual cleanup, timezone-aware datetimes, HTTP calls with timeouts.

Which repositories get it

A repository on this profile: service-python. redline init detects the profile and --profile overrides it — see Profiles & stacks.

Within such a repository, a file gets these rules when it matches one of these globs:

  • **/*.py

The 28 rules

When a review comment cites one of these ids, this is where to look up what it catches. Of the 28, 9 BLOCKER, 15 HIGH and 4 SUGGESTION. A finding from this file opens like this:

a finding from this file
Redline/BLOCKER [python/mutable-default-argument]: <one-line problem>

What each severity obliges you to do is on The output contract.

Rule idSeverityCatches
python/mutable-default-argumentBLOCKERMutable default arguments (`def f(items=[])`) — shared across calls; use `None` + assign inside.
python/bare-exceptBLOCKERBare `except:` or `except Exception: pass` — catch specific exceptions; never silence. Bare `except` also eats `KeyboardInterrupt`/`SystemExit`.
python/sql-string-interpolationBLOCKERSQL built with f-strings/`%`/`.format` from external input — parameterized queries only.
python/subprocess-shell-injectionBLOCKER`subprocess` with `shell=True` on anything derived from external input; prefer list-form argv always.
python/dynamic-code-executionBLOCKER`eval`/`exec`/`pickle.loads` on external data.
python/blocking-in-asyncBLOCKERBlocking calls inside `async def`: `requests`, `time.sleep`, sync DB drivers — use `httpx`/`aiohttp`, `asyncio.sleep`, async drivers, or `run_in_executor`.
python/secrets-not-centralisedBLOCKERSecrets hardcoded or read ad hoc — central config module, validated at startup.
python/call-in-default-argumentBLOCKERA function call as a default argument (`def f(at=datetime.now())`, `def f(cache=make_cache())`). It runs once, at definition, so every call shares one stale timestamp or one mutable object. Default to `None` and call it inside. Not for framework markers built for this (FastAPI `Depends`/`Query`, pydantic `Field`, dataclass `field(...)`) or calls returning immutable values (`timedelta(...)`).
python/return-in-finallyBLOCKER`return`, `break` or `continue` inside `finally`. It discards any exception raised in the `try`/`except`, so `charge()` raising `PaymentDeclined` still returns `{"ok": True}`. `finally` releases resources; move the jump out.
python/missing-type-hintsHIGHMissing type hints on new public functions — new code is typed; assume mypy/pyright strict.
python/missing-context-managerHIGHFiles/connections/locks without context managers (`with`) — leaks on exception paths.
python/module-level-mutable-stateHIGHModule-level mutable state used as implicit singleton across requests (Lambda warm starts share it — intentional caching must be explicit and documented).
python/broad-except-in-loopHIGHBroad `except Exception` that logs and continues in loops — one poisoned item must not silently vanish; dead-letter or re-raise policy required.
python/naive-datetimeHIGHDatetime handling: naive `datetime.now()` in new code — `datetime.now(timezone.utc)` and timezone-aware throughout.
python/assert-for-validationHIGH`assert` for runtime validation — stripped under `-O`; raise proper exceptions.
python/boto3-client-per-callHIGHBoto3 clients created per call inside handlers/loops — create at module scope (Lambda) or inject.
python/http-call-without-timeoutHIGHUnbounded `requests`/`httpx` calls without timeout.
python/loop-variable-closureHIGHA `lambda` or nested `def` created in a loop that reads the loop variable and runs after the iteration (stored, registered, scheduled). Closures look the name up when called, so every one sees the last value — `[lambda: send(u) for u in users]` sends to the last user N times. Bind it at creation (`lambda u=u: …`, `functools.partial`).
python/zip-without-strictHIGH`zip()` over two or more iterables without `strict=`. It stops silently at the shortest, so `dict(zip(headers, row))` on a short CSV row drops columns. Pass `strict=True`, or `strict=False` where unequal lengths are intended. Not on Python below 3.10, or when one argument is infinite (`itertools.count`).
python/quadratic-accumulationHIGHBuilding a sequence by copying it each step — `sum(lists, [])`, `reduce(lambda a, b: a + b, lists)`, `acc = acc + [x]` or `acc = {acc, k: v}` in a loop. Each step allocates a new container, so the work grows quadratically. Use `itertools.chain.from_iterable`, a comprehension, or mutate a local accumulator.
python/blanket-suppressionHIGHA `# type: ignore`, `# pyright: ignore` or `# noqa` with no error code. It silences every error on the line, including ones introduced later — an `arg-type` bug added next month is hidden by an ignore meant for an untyped import. Name the code (`# type: ignore[import-untyped]`, `# noqa: F401`). In addition to `core/type-checker-suppression`: a ticket does not excuse a missing code.
python/error-log-without-tracebackHIGH`logger.error(...)` in an `except` block with no `exc_info=True` and no re-raise. The traceback is lost, so a `KeyError` from any of a dozen reads logs as the same one-line message. Use `logger.exception(...)` or pass `exc_info=True`.
python/broad-exception-assertionHIGH`pytest.raises(Exception)` / `assertRaises(Exception)` (or `BaseException`) with no `match=`. The test passes on any error — a `TypeError` from a typo included — so it proves nothing about the behaviour it names. Assert the specific type, or add a non-empty `match=`.
python/module-patchingHIGHPatching by dotted import path in tests — `patch("app.billing.client.post")`, `mocker.patch("…")`, `monkeypatch.setattr("pkg.mod.attr", …)`. The test replaces the import graph, so it stays green when the real wiring breaks and goes red on a harmless move. Inject the dependency and pass a faithful test implementation. Not `patch.object` on an injected collaborator, `patch.dict(os.environ)` or `monkeypatch.setenv`.
python/prefer-typed-modelsSUGGESTIONDataclasses/pydantic models over dict-shaped data crossing function boundaries.
python/prefer-pathlibSUGGESTION`pathlib` over `os.path` string juggling in new code.
python/prefer-f-stringsSUGGESTIONf-strings over `%`/`.format`.
python/prefer-comprehensionsSUGGESTIONComprehensions over `map`/`filter` with lambdas; but no nested comprehensions beyond two levels.

Changing a rule

Edit standards/stacks/python.md and nowhere else. Every other copy is generated from it. A merged change reaches every onboarded repository as a pull request, so treat it as a production change.

Rule ids are permanent. Reword a rule freely; it keeps its id. Renaming or removing an id orphans every telemetry record that cited it.

  1. Edit the markdownstandards/ is the only place a human edits a rule. AGENTS.md, CLAUDE.md, .github/copilot-instructions.md and .github/instructions/ are rendered from it, and the next render overwrites any hand edit there.
  2. node scripts/assign-rule-ids.mjsAssigns a permanent <stack>/<slug> id to any new rule bullet and rewrites the file in place. Do not invent an id by hand. CI runs the same script with --check and fails if a rule is missing one.
  3. node scripts/render-self.mjsRe-renders this repository's own copies of those files. CI runs it with --check, so a stale copy fails the build.
  4. Bump standards/manifest.json → versionIn the same pull request as the rule change. Sync pull requests quote the version, so every repository can tell which standards it is on.
  5. Add a CHANGELOG.md entryAlso in the same pull request. Say what changed and why, and record the seed score: a standards change with no measurement is an opinion.
  6. node scripts/validate.mjsThe self-check CI runs: the manifest is consistent, rule ids are well formed, the output contract is intact, and every glob is one Copilot can read.

The full file

standards/stacks/python.md · 65 lines · 5.8 KB
# Python Review Rules

## BLOCKER — request changes

- `python/mutable-default-argument` — **Mutable default arguments** (`def f(items=[])`) — shared across calls; use `None` + assign inside.
- `python/bare-except` — **Bare `except:` or `except Exception: pass`** — catch specific exceptions; never silence. Bare `except` also eats `KeyboardInterrupt`/`SystemExit`.
- `python/sql-string-interpolation` — **SQL built with f-strings/`%`/`.format` from external input** — parameterized queries only.
- `python/subprocess-shell-injection` — **`subprocess` with `shell=True`** on anything derived from external input; prefer list-form argv always.
- `python/dynamic-code-execution` — **`eval`/`exec`/`pickle.loads` on external data.**
- `python/blocking-in-async` — **Blocking calls inside `async def`**: `requests`, `time.sleep`, sync DB drivers — use `httpx`/`aiohttp`, `asyncio.sleep`, async drivers, or `run_in_executor`.
- `python/secrets-not-centralised` — **Secrets hardcoded or read ad hoc** — central config module, validated at startup.
- `python/call-in-default-argument` — **A function call as a default argument** (`def f(at=datetime.now())`,
  `def f(cache=make_cache())`). It runs once, at definition, so every call shares one stale timestamp or one
  mutable object. Default to `None` and call it inside. Not for framework markers built for this (FastAPI
  `Depends`/`Query`, pydantic `Field`, dataclass `field(...)`) or calls returning immutable values
  (`timedelta(...)`).
- `python/return-in-finally` — **`return`, `break` or `continue` inside `finally`.** It discards any exception
  raised in the `try`/`except`, so `charge()` raising `PaymentDeclined` still returns `{"ok": True}`. `finally`
  releases resources; move the jump out.

## HIGH

- `python/missing-type-hints` — Missing type hints on new public functions — new code is typed; assume mypy/pyright strict.
- `python/missing-context-manager` — Files/connections/locks without context managers (`with`) — leaks on exception paths.
- `python/module-level-mutable-state` — Module-level mutable state used as implicit singleton across requests (Lambda warm starts share it — intentional caching must be explicit and documented).
- `python/broad-except-in-loop` — Broad `except Exception` that logs and continues in loops — one poisoned item must not silently vanish; dead-letter or re-raise policy required.
- `python/naive-datetime` — Datetime handling: naive `datetime.now()` in new code — `datetime.now(timezone.utc)` and timezone-aware throughout.
- `python/assert-for-validation` — `assert` for runtime validation — stripped under `-O`; raise proper exceptions.
- `python/boto3-client-per-call` — Boto3 clients created per call inside handlers/loops — create at module scope (Lambda) or inject.
- `python/http-call-without-timeout` — Unbounded `requests`/`httpx` calls without timeout.
- `python/loop-variable-closure` — **A `lambda` or nested `def` created in a loop that reads the loop variable
  and runs after the iteration** (stored, registered, scheduled). Closures look the name up when called, so
  every one sees the last value — `[lambda: send(u) for u in users]` sends to the last user N times. Bind it at
  creation (`lambda u=u: …`, `functools.partial`).
- `python/zip-without-strict` — **`zip()` over two or more iterables without `strict=`.** It stops silently at
  the shortest, so `dict(zip(headers, row))` on a short CSV row drops columns. Pass `strict=True`, or
  `strict=False` where unequal lengths are intended. Not on Python below 3.10, or when one argument is infinite
  (`itertools.count`).
- `python/quadratic-accumulation` — **Building a sequence by copying it each step** — `sum(lists, [])`,
  `reduce(lambda a, b: a + b, lists)`, `acc = acc + [x]` or `acc = {**acc, k: v}` in a loop. Each step allocates
  a new container, so the work grows quadratically. Use `itertools.chain.from_iterable`, a comprehension, or
  mutate a local accumulator.
- `python/blanket-suppression` — **A `# type: ignore`, `# pyright: ignore` or `# noqa` with no error code.** It
  silences every error on the line, including ones introduced later — an `arg-type` bug added next month is
  hidden by an ignore meant for an untyped import. Name the code (`# type: ignore[import-untyped]`, `# noqa:
  F401`). In addition to `core/type-checker-suppression`: a ticket does not excuse a missing code.
- `python/error-log-without-traceback` — **`logger.error(...)` in an `except` block with no `exc_info=True` and
  no re-raise.** The traceback is lost, so a `KeyError` from any of a dozen reads logs as the same one-line
  message. Use `logger.exception(...)` or pass `exc_info=True`.
- `python/broad-exception-assertion` — **`pytest.raises(Exception)` / `assertRaises(Exception)` (or
  `BaseException`) with no `match=`.** The test passes on any error — a `TypeError` from a typo included — so it
  proves nothing about the behaviour it names. Assert the specific type, or add a non-empty `match=`.
- `python/module-patching` — **Patching by dotted import path in tests** — `patch("app.billing.client.post")`,
  `mocker.patch("…")`, `monkeypatch.setattr("pkg.mod.attr", …)`. The test replaces the import graph, so it stays
  green when the real wiring breaks and goes red on a harmless move. Inject the dependency and pass a faithful
  test implementation. Not `patch.object` on an injected collaborator, `patch.dict(os.environ)` or
  `monkeypatch.setenv`.

## SUGGESTION

- `python/prefer-typed-models` — Dataclasses/pydantic models over dict-shaped data crossing function boundaries.
- `python/prefer-pathlib` — `pathlib` over `os.path` string juggling in new code.
- `python/prefer-f-strings` — f-strings over `%`/`.format`.
- `python/prefer-comprehensions` — Comprehensions over `map`/`filter` with lambdas; but no nested comprehensions beyond two levels.