Skip to content
Sarj Code Standards

Python rules

222 rules

Rule Category Introduced
Py async-cleanup-registered-synchronously Do not register a proven async cleanup function with ExitStack.callback. correctness
Py async-executor-shutdown Run waiting executor shutdown outside the async event-loop thread. correctness
Py async-mock-call-without-await-assertion Pair positive AsyncMock call assertions with evidence that the mock was awaited. testing
Py async-subprocess-cancellation-cleanup Settle locally owned asyncio subprocesses when their caller is cancelled. correctness
Py cancel-owned-task-without-join Join a cancelled locally owned task before releasing its lifecycle. correctness
Py complex-postgres-query-requires-architecture-review Complex executable PostgreSQL query shapes require architecture review. architecture
Py defect-xfail-requires-explicit-strict A deterministic known-defect `xfail` must set literal `strict=True` so XPASS fails the suite. testing
Py delete-route-returns-no-content FastAPI DELETE routes declare status code 204 No Content. correctness
Py docstring-args-restate-signature Remove a wholly redundant Google-style Args section when every entry only repeats the function signature. maintainability
Py docstring-returns-restate-signature Google-style Returns and Yields documentation must add facts beyond the corresponding annotated result type. maintainability
Py duplicate-adjacent-exception-handler Adjacent exception handlers repeat the same executable translation. maintainability
Py duplicate-closed-pure-helper Closed private helpers repeat one proven native regex/string transformation. maintainability
Py duplicate-pytest-fixture-params Review repeated immutable values in a pytest fixture parameter list. testing
Py excessive-commentary Delete comment paragraphs that exactly repeat the following ordered action names. maintainability
Py failed-probe-zero-threshold Do not let a failed subprocess count probe meet its threshold through a zero fallback. correctness
Py fakes-in-shared-location Review named top-level test doubles for shared-support ownership unless they are intentionally scenario-local. testing
Py fastapi-class-router-contract FastAPI HTTP routes use injected `*Router.build()` owners and explicit named object response models. architecture
Py fastapi-explicit-openapi-contract Visible FastAPI operations pin locally reviewable metadata and avoid statically provable OpenAPI gaps. correctness
Py fastapi-route-declares-security Declare each FastAPI route access decision, including inherited router dependencies. security
Py iac-source-coupled-test Test uses raw Terraform/HCL text as an infrastructure-behavior oracle. testing
Py invalid-pydantic-field-default Require literal Pydantic model-field defaults to satisfy their resolved contract. correctness
Py mock-without-spec Unrestricted mock permits attributes outside the collaborator contract. testing
Py named-record-at-boundaries Public Python API returns an unnamed fixed-shape record. architecture
Py nan-hidden-by-builtin-min Validate floating candidates before a built-in min/max can hide a NaN. correctness
Py negative-only-http-status-assertion HTTP test assertion only excludes a server error instead of identifying the intended response. testing
Py no-analytical-aggregation-in-postgres-store Keep DISTINCT, GROUP BY, and SQL aggregates in analytical databases. architecture
Py no-any-mapping-types String-keyed mapping types must not erase their values with `Any`. correctness
Py no-async-client-in-constructor Inject an HTTPX AsyncClient instead of constructing one in __init__. architecture
Py no-async-function-cache Standard library cache decorates a coroutine function and retains single-use coroutine objects. correctness
Py no-bare-test-phase-comments Test files must not use bare phase comments such as Arrange, Act, Assert, Given, When, or Then. testing
Py no-before-validator-input-mutation Preserve raw inputs in Pydantic before validators. correctness
Py no-blanket-suppression Use named, line-local suppressions instead of blanket, file or range disables. correctness
Py no-broad-keyword-capture Prefer precise keyword interfaces over missing, Any- or object-valued captures. maintainability
Py no-comment-cruft Commented-out code, mechanical narration, decorative banner, or untracked work marker. maintainability
Py no-conflicting-pydantic-alias-validation Pydantic alias configuration must retain a validation path. correctness
Py no-conftest-test-module-import Do not import individual test modules from conftest.py. testing
Py no-contradictory-type-guard Primitive type guards must agree with the builtin predicate they return. correctness
Py no-copied-inherited-docstring An override repeats the documentation of the single local base method it actually overrides. maintainability
Py no-cors-wildcard-with-credentials Credentialed CORS must not allow a wildcard origin. security
Py no-create-verb-in-post-path POST routes name their collection instead of ending in a create, add or new segment. architecture
Py no-custom-control-flow-exception Return coded typed outcomes for expected domain failures instead of exception-only contracts. architecture
Py no-database-programmability Keep stored SQL functions and triggers out of embedded SQL. architecture
Py no-defaulted-environment-setting A settings field that names the deployment environment must not declare a default. correctness
Py no-delete-statement Avoid `del` statements; prefer constructing an immutable replacement value. maintainability
Py no-discarded-tagged-outcome Handle a returned tagged outcome instead of discarding it. correctness
Py no-discarded-validation-result Consume a value-producing validator's result instead of relying on its exceptions. correctness
Py no-docstring-type-restatement A docstring type label repeats an annotation from the fully typed signature. maintainability
Py no-dual-shape-model-field-reader Normalize a known model instead of reading its fields through a model-or-dict accessor. maintainability
Py no-dunder-all modules should not define or mutate `__all__` maintainability
Py no-duplicate-dunder-all-entry static module `__all__` declarations should list each exported name once correctness
Py no-duplicate-field-validator-body Pydantic field validators in one model repeat the same body. maintainability
Py no-dynamic-builtins Use explicit typed state instead of dynamic Python builtin access. maintainability
Py no-exception-text-in-500-detail HTTP 500 exception details must not carry exception text or tracebacks. security
Py no-excessive-cognitive-complexity Error on cognitive complexity above 20; scores up to 20 pass. maintainability
Py no-fastapi-on-event Deprecated FastAPI or Starlette on_event lifecycle registration. correctness
Py no-file-level-escape-hatch-suppression File-level Ruff suppression disables an escape-hatch rule across the entire file. maintainability
Py no-first-party-private-import A first-party consumer imports a private name or private module across its package boundary. architecture
Py no-fixed-sleep-before-assert Do not sleep for a fixed interval and then assert in a test. testing
Py no-fixed-sleep-in-loop Do not sleep for a fixed literal interval inside a production loop. testing
Py no-folded-bad-request-not-found Do not handle HTTP 400 and 404 statuses in one branch. correctness
Py no-frozen-after-validator-field-write Do not assign declared fields in after-validators on frozen Pydantic models. correctness
Py no-generic-json-parser Parse consumed JSON fields with a bespoke declarative model instead of an open JSON parser. correctness
Py no-generic-single-export-module A generic module name should not conceal a single-definition responsibility. architecture
Py no-hasattr Do not probe attributes with the builtin hasattr. maintainability
Py no-hidden-constructor-fallback Constructor option silently falls back to application settings when omitted. architecture
Py no-impossible-pydantic-field-bounds Pydantic field bounds must admit at least one value. correctness
Py no-injected-module-loader Avoid a generic module-loader parameter used only to import one fixed module. architecture
Py no-input-model-mutation Return replacement values instead of mutating caller-owned Pydantic models. correctness
Py no-interpreter-source-arguments Keep interpreter programs in linted files or modules, outside process argv and literal Python stdin. architecture
Py no-invalid-argument-name-suppression External parameter spelling must use framework aliases instead of disabling snake_case naming. maintainability
Py no-invalid-pydantic-bypass Do not create a provably invalid model through Pydantic validation bypass APIs. correctness
Py no-invalid-pydantic-validator-return A terminal field validator must not return a literal contradicting its stored field type. correctness
Py no-loguru-exc-info Loguru exc_info=True adds a field rather than retaining the exception traceback. correctness
Py no-loguru-printf-format Use brace formatting for positional values passed to Loguru. correctness
Py no-magic-arithmetic Name nontrivial numeric factors and operational limits. maintainability
Py no-mocked-pydantic-value-object Build real Pydantic models when test doubles supply model field data. testing
Py no-mutating-container-transform Return container replacements without mutating borrowed builtin inputs. correctness
Py no-mutating-input-with-result Separate input attribute mutation from functions that return a result. correctness
Py no-nested-pydantic-field-validator Outer-model Pydantic field validator is owned by a nested helper class. correctness
Py no-nullable-dependency-fallback Require concrete function dependencies instead of resolving a None default inside the function. architecture
Py no-offset-pagination Potentially unbounded `OFFSET` pagination in store SQL. performance
Py no-partial-type-is TypeIs must not reject a value belonging to its declared target type. correctness
Py no-positional-psycopg-row-escape A positional Psycopg record must not escape its function unchanged. correctness
Py no-positional-tuple-record Fixed tuple return records should use named fields instead of positional slots. maintainability
Py no-provably-dead-mock-configuration Remove mock behavior configuration proven unable to affect a test. testing
Py no-psycopg-execution-in-loop Use bounded bulk queries instead of executing Psycopg operations inside item loops. performance
Py no-psycopg-execution-outside-injected-owner Psycopg execution occurs outside a constructor-injected persistence owner. architecture
Py no-random-uuid-in-sql Embedded SQL generates a random UUIDv4 instead of a time-ordered UUIDv7. performance
Py no-raw-connection-in-tests Do not execute raw SQL or acquire raw database connections in tests. testing
Py no-raw-source-text-test-oracle Test uses raw text from a source-like project path as its oracle. testing
Py no-recording-store Use the PostgreSQL store in tests instead of a recording-only store implementation. testing
Py no-redundant-attribute-unpacking Use an aggregate's named attributes instead of repeating their names in tuple aliases. maintainability
Py no-redundant-local-alias Remove a local alias used only for its matching keyword argument. maintainability
Py no-redundant-module-alias-exports Do not manufacture public APIs from private names or replace the current module. maintainability
Py no-redundant-sql-alias Remove SQL aliases that repeat the original relation or column name. maintainability
Py no-repeated-structured-string-literal Exact SQL or route literals repeated across callable scopes should share one named binding. maintainability
Py no-repeated-test-body Substantial sibling pytest tests repeat the same structural body. testing
Py no-repeated-unseeded-stdlib-random-in-test A collected test may repeatedly sample an unseeded standard-library PRNG. testing
Py no-restated-closed-domain-description Do not restate a string Literal or local string Enum domain in its Pydantic description. maintainability
Py no-restated-comment Short standalone comment lexically restates the immediately following simple action. maintainability
Py no-secret-in-log A direct credential-like reference is passed to a recognized logging call. security
Py no-select-star SQL SELECT projections should list explicit result columns instead of wildcards. maintainability
Py no-service-behavior-in-settings Settings and configuration types should not orchestrate injected collaborators. architecture
Py no-shallow-container-type-guard Do not claim typed container contents from a container-only type guard. correctness
Py no-shallow-record-type-guard Do not promise a local record's contract from a container-only check. correctness
Py no-shared-mutable-default Do not share mutable function defaults through aliases or read-only annotations. correctness
Py no-slash-collection-root-under-prefix A collection-root route under a literal router prefix uses an empty path instead of a slash. correctness
Py no-statically-truthy-assertion An assertion condition is statically truthy, including deferred expressions and test-local scalar setup. testing
Py no-string-concat-in-loop Avoid repeatedly growing a proven string accumulator across a loop backedge. performance
Py no-swallowed-asyncio-cancellation Preserve cancellation when an async operation is cancelled. correctness
Py no-sys-path-mutation Do not mutate the interpreter import search path. correctness
Py no-test-comments Express test behavior in names and assertions instead of ordinary comments. testing
Py no-test-method-grafting Avoid assigning replacement implementations directly onto resolved methods in tests. testing
Py no-trailing-numeric-unit-assignment-comment A trailing comment redundantly labels a numeric assignment with its value and unit. maintainability
Py no-unique-violation-message-match Do not make unique-violation control flow depend on rendered exception text. correctness
Py no-unknown-pydantic-validator-field Pydantic field decorators must target declared fields. correctness
Py no-unnecessary-docstring No docstring consumer detected — delete it; make author-controlled names, types, and structure explain the code. maintainability
Py no-unused-copy-result Use the replacement returned by a resolved copy API. correctness
Py no-unused-underscored-keyword-parameter Remove unused underscore-prefixed keyword-only parameters instead of hiding them from lint. maintainability
Py no-unused-value-marker Do not use standalone assignments to `_` to discard values. maintainability
Py no-vague-suppression-description Suppressions need a concrete description of the exception. maintainability
Py no-whole-request-response-payload-in-log Whole request or response payloads passed to logging calls require review. security
Py no-work-verb-get-route GET routes must not end in a work verb such as run, send, trigger or retry. security
Py numeric-literal-separators Group long decimal numeric literals with thousands separators. maintainability
Py opaque-parametrize-case-needs-id Opaque static pytest parameter cases lack table-local semantic IDs. testing
Py over-mocked-test Tests should not use more than five independently rooted test doubles or collaborator substitutions. testing
Py prefer-application-model-joins Compose distinct model records in application code instead of a cross-model SQL join. architecture
Py prefer-autospec-for-callable-mock Prefer autospec for specced function mocks called with explicit keywords. testing
Py prefer-bulk-upsert Use declared compatible bulk APIs for repeated singleton reads and writes. performance
Py prefer-class-row Avoid fetching a Psycopg dictionary row only to construct the same model manually. maintainability
Py prefer-collection-comprehension Single-purpose fresh collection builder loop — prefer a direct comprehension. style
Py prefer-configured-cloud-scope Read Cloudflare account targets from validated deployment configuration. architecture
Py prefer-constant-time-secret-compare Externally supplied authenticators are compared with timing-sensitive equality. security
Py prefer-coordinated-state-owner Review dictionaries with repeated same-key writes and removals for one typed owner. architecture
Py prefer-declarative-batch-validation Validate a homogeneous Pydantic batch with a declared collection contract. maintainability
Py prefer-direct-import-module Prefer static imports for eager module loads with a literal module name. style
Py prefer-discriminated-model-union Give data unions explicit Literal discriminators and express tag-dependent payloads as variants. architecture
Py prefer-explicit-class-contract Declare a contract for a stateful behavior class. architecture
Py prefer-fstring-over-concat Prefer f-strings for short human-readable interpolation when they make the result clearer. style
Py prefer-grouped-settings Group settings fields that share a Python namespace prefix into a nested settings object. architecture
Py prefer-immutable-module-constant Module collection constants should use native immutable containers or declare their bindings as Final. maintainability
Py prefer-injected-dependency-over-monkeypatch Prefer explicit test dependencies; justify scoped attribute patches at the boundary. testing
Py prefer-injected-service Inject a service instead of constructing it from dependencies already available to the consumer. architecture
Py prefer-library-fake Prefer a maintained fake, emulator, recorder, or test service for substantial third-party protocols. testing
Py prefer-match-assert-never Typed enum dispatch must not silently ignore unhandled members. correctness
Py prefer-match-exception-dispatch Prefer guarded match/case for refined exception type dispatch. maintainability
Py prefer-match-type-dispatch Prefer `match` for structural runtime type dispatch. maintainability
Py prefer-match-value-dispatch Prefer match/case for repeated dispatch on one value with a fallback. maintainability
Py prefer-module-level-constant Hoist repeatedly read static values when a module constant preserves behavior. performance
Py prefer-monkeypatch-for-process-state-in-test Test mutates process-wide state without a restoring test scope. testing
Py prefer-monotonic-for-elapsed-time Use a monotonic clock for a local wall-clock value used only to measure elapsed time. correctness
Py prefer-native-string-check Avoid unconstrained adapters for string assertions or already encoded JSON mappings. maintainability
Py prefer-nominal-id-types Python boundaries should distinguish swappable identifier roles with nominal types. correctness
Py prefer-nominal-mapping-keys Declare record shapes or nominal keys at primitive-keyed mapping boundaries. architecture
Py prefer-non-nullable-collection Avoid nullable list parameters that are immediately collapsed to an empty list. maintainability
Py prefer-optional-composite Review related optional fields as one optional composite value. maintainability
Py prefer-or-pattern Merge adjacent `case` arms with identical bodies into one or-pattern. maintainability
Py prefer-outcome-variants Express nullable success and error state as tagged outcome variants. architecture
Py prefer-precise-object-contract Use a precise type for declared application contracts instead of object. maintainability
Py prefer-psycopg-executemany Use Psycopg executemany for a serial loop of invariant parameterized writes without row results. performance
Py prefer-pydantic-json-value Recursive JSON value alias duplicates `pydantic.JsonValue`. correctness
Py prefer-pydantic-model-assertion Compare a Pydantic model or an explicit field projection instead of consecutive property assertions. testing
Py prefer-pytest-dependency-fixtures Reuse supplied pytest fixtures and pass test collaborators through fixture dependencies. testing
Py prefer-pytest-fixture-contract Expose existing abstract contracts from pytest fixtures and injected parameters. testing
Py prefer-pytest-fixture-injection Request shared database-pool setup through a pytest fixture. testing
Py prefer-regex-fullmatch An anchored regex validation predicate does not require a full-string match. correctness
Py prefer-required-constructor-parameters Prefer required constructor parameters so callers choose dependencies and configuration explicitly. architecture
Py prefer-runtime-validation Prefer runtime validation to TypeGuard assertions. maintainability
Py prefer-self-documenting-constant Encode a constant's units or HTTP status meaning in its name, type, or value. maintainability
Py prefer-self-type-annotation Prefer `Self` for self-returning methods and alternate constructors. maintainability
Py prefer-set-isdisjoint Prefer `set.isdisjoint` when a built-in set intersection is used only as a boolean predicate. style
Py prefer-single-psycopg-cursor Review repeated Psycopg cursor creation within one function. maintainability
Py prefer-str-enum Prefer `StrEnum` for application-owned string domains with explicit closed-set evidence. maintainability
Py prefer-struct-over-namedtuple Prefer typed declarations for static application-owned `collections.namedtuple` records. maintainability
Py prefer-typed-cli Declare CLI arguments with typed Typer commands. maintainability
Py prefer-typed-mapping-get Read named fields from typed records instead of schema-free mappings. maintainability
Py prefer-typed-settings-field Declare numeric model domains and use typed choices for token-valued defaults. maintainability
Py prefer-validated-uuid-comparison Validate UUID identifiers at input boundaries before comparing them. architecture
Py prefer-walrus-awaited-none-guard Bind a compact awaited lookup in its immediately following terminal None guard. style
Py prefer-walrus-comprehension-filter The same call runs in a comprehension filter and its result. performance
Py prefer-walrus-regex-match A proven regex Match-or-None result is assigned only for the following condition. style
Py prefer-walrus-stream-loop Collapse a compact producer assignment and immediate sentinel break into a named-expression loop. style
Py production-derived-test-cases Warn when pytest membership-contract cases are derived only from the first-party production collection. testing
Py pytest-fixture-returns-bare-tuple Pytest fixture exposes a fixed positional record as an unnamed tuple. testing
Py pytest-fixture-returns-closed-resource Yield a managed fixture resource until its requesting test finishes. testing
Py redundant-class-docstring Undecorated base-free class docstring only repeats the class name. maintainability
Py redundant-docstring Function or plain-method docstring only repeats its declaration. maintainability
Py redundant-module-docstring Delete top-of-file module docstrings without a detected runtime or documentation consumer. maintainability
Py redundant-test-constructor-forwarder A private test helper mirrors a resolved value-record constructor without adding a contract. testing
Py repeated-kwarg-heavy-call-in-test Tests repeat at least seven explicit keyword names across calls to the same callee. testing
Py repeated-static-call-cases Three same-shape literal call assertions may be independent parameter cases. testing
Py repeated-test-composition Sibling tests repeat service collaborator wiring or managed ASGI HTTP clients. testing
Py repeated-unimplemented-test-contract Share repeated typed fail-fast abstract operations between test fakes. testing
Py replay-contract-insert-requires-duplicate-policy A literal INSERT in a replay-named store callable must declare duplicate behavior. correctness
Py require-constrained-api-integer Declare numeric bounds for scalar integer FastAPI request parameters. correctness
Py require-exp-on-jwt-decode PyJWT decode calls require the exp claim. security
Py require-explicit-contract-implementation Require owned substitutes to inherit an injected nominal abstract contract. architecture
Py require-explicit-psycopg-transaction Make Psycopg locking reads and related writes explicitly transactional. correctness
Py require-explicit-service-contract Require an explicit contract for services that invoke collaborators or perform HTTP operations. architecture
Py require-injectable-retry-sleep Pass an injectable sleep to a tenacity retry policy that waits between attempts. testing
Py require-keyword-only-swap-prone-params Risky-name positional parameters sharing a primitive annotation may be confused. correctness
Py require-nodecode-for-splitting-settings-field Warn when an unconditional raw-string splitter lacks a pydantic-settings decoding policy. correctness
Py require-port-for-service Consider a consumer-owned port when visible service structure suggests a substitution boundary. architecture
Py require-precise-factory-signature Keep fixed keyword factory calls behind a precise callable signature. architecture
Py require-public-dependency-contract Reuse an existing substitutable contract instead of its concrete implementation annotation. architecture
Py require-pydantic-for-external-json Proven external JSON record fields are consumed before runtime schema validation. correctness
Py require-pydantic-for-mapping-shape Declare opaque mapping field shapes in Pydantic instead of probing them by hand. maintainability
Py require-pydantic-for-structured-payload Structured nested FastAPI payloads must be parsed into a named Pydantic model before field access. correctness
Py require-pydantic-ordinal-lower-bound A Pydantic ordinal field maps its first position to N but accepts smaller integers. correctness
Py restated-test-docstring Collected test docstring only repeats names and visible code. testing
Py service-singleton-delegates-to-bulk Service singleton CRUD operations must delegate to a bulk primitive. architecture
Py shared-mutable-pydantic-factory Pydantic default factories should not return a captured mutable singleton. correctness
Py stepdown A private helper used by one caller should be defined below that caller. maintainability
Py store-field-update-reuses-upsert A plain field UPDATE duplicates fields already writable through the store's upsert command. maintainability
Py store-get-delegates-to-bulk-read A store singleton operation should reuse its equivalent bulk implementation. maintainability
Py store-insert-requires-explicit-conflict-policy Declare SQL conflict behavior for store INSERT statements, including fixture writes. correctness
Py store-mutation-command-fanout Review per-field store mutations beside an existing model write command. architecture
Py subprocess-kill-without-reap Reap a locally owned subprocess after killing it on timeout. correctness
Py test-without-explicit-oracle A collected test has no visible assertion or exception oracle. testing
Py timestamp-order-requires-tiebreaker Bounded store SQL whose final result-order key looks like a `*_at` timestamp should include a deterministic secondary key. correctness
Py typed-error-reasons Review joined exception strings for fixed reason identities versus dynamic context. architecture
Py unused-test-factory-option A private test factory exposes an invariant literal or unexercised local callable option. testing