Python Standard

*Status:* authoritative · Source: the ft-python-standards skill · Applies to: Python in FT repos (ft-internal-tools, ft-agent-platform-local)

The standard for FT Python code, read by developers and reviewers in ft-internal-tools and ft-agent-platform-local. This page is the readable form of the ft-python-standards skill. If they differ, the skill wins. Report the difference. The skill overrides any other Python standard.

Java (Java standard) and Angular have their own standards. Their numeric limits, dependency injection style and exception conventions do not apply to Python. Quoting a Java threshold at Python code is a review defect.

Legend: Do is required practice. Don’t is forbidden. Target means the practice is not yet true everywhere, so do it in new code. [MUST-FIX] is a blocking review finding.

Table 1. On this page
Sections Topic

P1 · Toolchain: the config is the standard-P3 · Type annotations are a contract

toolchain, layout, types

P4 · Immutability by default-P8 · Building blocks: reach for these first

immutability, dependencies, logging, exceptions, building blocks

P9 · Function and module discipline-P10 · Tests

function and module limits, tests

P11 · Flask HTTP surfaces-P13 · Concurrency, asyncio, timeouts

Flask, subprocess and filesystem, concurrency

P-DB · SQLAlchemy sessions, queries and route authorization, P14 · Dependencies and migrations, P15 · Security baseline (code level), P16 · Comments and docstrings

SQLAlchemy, dependencies and Alembic, security, comments

Review checklist

one-screen check before review

Where the standard comes from

The standard takes the better practice of the two Python codebases as the rule. The other practice is the migration target. The table below was measured on 2026-08-31. The counting command was not recorded.

Both columns use one method: test paths are excluded, functions are counted by AST (abstract syntax tree), and "annotated" means a return type and every parameter are typed.

The agent platform counts 359 uses of @dataclass(frozen=True) here and 357 uses of @dataclass(frozen=True, slots=True) in P4 · Immutability by default. The two counts use different patterns. Neither count is verified, because the repositories are not in this checkout.

ft-internal-tools (251 modules, Flask) ft-agent-platform-local (190 modules)

Fully annotated functions

58% (974 of 1683)

100% (1975 of 1975)

f-strings inside log calls

46% (183 of 401)

0 (of 1)

Uses of @dataclass(frozen=True)

51

359, the dominant shape

Tooling config

none

ruff and mypy strict, Python 3.14, line length 100

shell=True

0

0

Where this standard is silent, the baseline is PEP 8, PEP 20 and the ruff config of the repository.

P1 · Toolchain: the config is the standard

pyproject.toml is the single source of configuration. It holds build, dependencies, ruff, mypy and pytest. Do not use setup.py, setup.cfg, .flake8 or requirements.txt as the source of truth in a new project.

Use ruff for lint and format. It replaces flake8, isort, black, pyupgrade and pylint. The FT baseline comes from ft-agent-platform-local:

[tool.ruff]
target-version = "py312"      # py314 where the repo already requires it
line-length = 100
src = ["src", "tests"]

[tool.ruff.lint]
select = ["E", "F", "W", "I", "UP", "B", "SIM", "C4", "RET", "PL", "RUF"]

[tool.mypy]
strict = true
files = ["src", "tests"]
Rule set Checks

E, F, W

pycodestyle and pyflakes

I

import order

UP

modern syntax

B

bugbear (the mutable default, the loop-variable closure)

SIM, C4, RET

simplify, comprehensions, returns

PL, RUF

pylint core, ruff’s own rules

  • Set line-length = 100, not black’s 88. The estate uses 100, and consistency inside FT beats the upstream default.

  • Use mypy strict. Without it, unannotated functions are skipped silently, so the type checker reports success on the code that needs it most.

  • A per-module ignore_missing_imports override is fine with a comment that names the library and the reason. Never use it as a blanket switch.

  • Use uv for environments, locking and builds where the repository has adopted it. Otherwise follow the repository. Never mix two package managers in one repository.

  • Python 3.12 is the minimum for new code. Match requires-python of the repository where it is higher.

  • Target: a repository with no ruff or mypy config gets one before its next significant change. Start with the select list above and non-strict mypy on the touched package. Tighten as it goes green. Do not reformat the whole repository in a feature pull request, because that buries the change.

P2 · Layout: two legitimate shapes, one rule each

A distributable package, or a service with a domain, uses the src/ layout. It stops an accidental import of the repository root from shadowing the installed package.

src/ft_agent_platform/
├── domain/          # decisions, no I/O
├── contracts/       # the shapes crossing boundaries
├── adapters/        # the outside world
├── storage/
└── cli/             # wiring only
tests/{unit,integration,contract,property,fault,migration}/

A Flask tool inside the estate uses the layered shape, with features grouped inside each layer:

backend/
├── routes/<feature>/     # HTTP surface only
├── services/             # the decisions
├── repos/                # persistence
├── migrations/versions/  # Alembic
└── tests/

Rules for both shapes:

  • init.py is the contract of the module. A cross-module import that reaches past it into a submodule is a boundary violation. Either the name belongs in the contract, or the call does not belong.

  • No import cycles. A cycle means two modules are really one. Merge them or extract the shared piece. An import inside a function that avoids a cycle needs a comment that names the cycle.

  • The domain layer imports no framework. No flask, no ORM session and no HTTP types in code that makes decisions. This keeps the domain testable without a server.

  • Don’t create a top-level utils.py, helpers.py or common.py. A name that cannot say what belongs in the module collects everything. Name the module after its capability.

  • Entry points (main.py, cli.py, wsgi.py, app.py) contain wiring only.

P3 · Type annotations are a contract

Annotate every public function, both parameters and return. Annotate internal helpers when the type is not obvious two lines away.

def resolve_targets(plan: DeploymentPlan, env: str) -> list[DeviceId]:
  • Use builtin generics and unions: list[str], dict[str, int], X | None. Never use List or Optional.

  • Any is an admission, not a type. Model the variation with a TypedDict, a union or a Protocol. Otherwise take object and narrow it explicitly.

  • X | None obliges the caller to handle None. Annotating it and then dereferencing it unchecked is the bug the annotation looked like it prevented.

  • Prefer Protocol over an abstract base class for a seam you only need to satisfy structurally. It also keeps the domain free of adapter imports.

  • Target: the estate sits at 58% and 100% annotated. New and touched code is annotated. A module you change substantially ends better annotated than you found it. mypy strict on the touched package is the check.

P4 · Immutability by default

Use @dataclass(frozen=True, slots=True) for anything that carries values across a boundary. Examples are a request payload, a config and a domain fact. The agent platform has 357 uses of @dataclass(frozen=True, slots=True), which makes this the shape of the estate. Use tuple and frozenset for collections that must not change after construction.

@dataclass(frozen=True, slots=True)
class DeploymentTarget:
    device_id: DeviceId
    host: str
    port: int = 8080
  • Don’t use a mutable default argument (def f(items: list = [])). Ruff rule B006 catches it. The fix is None plus building inside, or field(default_factory=list).

  • Don’t mutate a module-level mutable (CACHE = {}) from functions. It is global state with no owner, it breaks test isolation and it races under threads. Own it in a class or pass it.

  • Don’t mutate the argument of a caller. Return a new value, or say it in the name (append_row).

  • Use pydantic to validate what crosses the wire. Its v2 model is the right tool at the edge. Frozen dataclasses are for what lives inside. Do not use a pydantic model as a domain entity just to get validation.

P5 · Dependency passing: explicit, at construction

Python needs no DI container. The rule is the same as in the Java standard, achieved differently.

class DeploymentService:
    def __init__(self, repo: DeploymentRepository, clock: Callable[[], datetime]) -> None:
        self._repo = repo
        self._clock = clock
  • Don’t run side effects at import time: opening a connection, reading a file or building a client at module scope. Importing must be free. Otherwise import order becomes a hidden dependency and the module cannot be tested without its infrastructure.

  • Don’t reach for a global inside a function body (from app import db). That is the dependency a test cannot replace.

  • Time, randomness, the filesystem and the environment are dependencies. Inject a clock, a Random and a base Path. If you need freezegun to control time, the clock was not injected.

  • In Flask, build the app in a factory (create_app()), register blueprints there and keep current_app out of services.

P6 · Logging: structured, greppable, never an f-string

logger = logging.getLogger(__name__)

logger.info("deployment started deployment_id=%s env=%s targets=%d",
            plan.id, plan.env, len(plan.targets))
  • Don’t put an f-string inside a log call. It formats even when the level is disabled and it destroys the message template that aggregation groups on. 46% of the internal-tools log calls do this today (183 of 401). It is the most common Python defect in the estate and not a style preference. Ruff rule G004 catches it. Enable the G rules where the repository can take the change.

  • Write key=value for every identifier, so support can grep one deployment out of a day of logs: deployment_id=…​, session_id=…​. For a device, log serial= (the serial number, a string) and deviceId= (a number). Add the session key when a session or transaction exists. The device keys are the same as in the Java standard, and so is the reason.

  • Use logger.exception(…​) inside except. It attaches the traceback. logger.error there throws the traceback away.

  • Write JSON output in production with python-json-logger. structlog is the sanctioned upgrade for a service that needs request-scoped context, because its contextvars binding survives asyncio boundaries and extra= does not. Choose once per service, not per module.

  • Don’t use print() outside the own output of a CLI. Don’t put secrets, tokens or full request bodies in a log line.

Level Use for

debug

flow

info

a business event

warning

degraded but handled

error

a failed operation

critical

the process cannot continue

P7 · Exceptions and error flow

  • Define one exception type for each failure a caller can act on differently, under one feature base: class DeploymentError(Exception), then class PlanConflictError(DeploymentError).

  • Don’t write a bare except:. It swallows KeyboardInterrupt and SystemExit.

  • Don’t write except Exception: pass. An error that is truly ignorable still needs a comment that says why, and a debug line.

  • Keep try blocks narrow. Wrap the call that can fail, not the twenty lines around it.

  • Use raise NewError(…​) from err when you translate an exception. Losing the cause loses the diagnosis.

  • Put clean-up in finally or a context manager. Never duplicate it on each exit path.

  • Don’t use exceptions as control flow across a module boundary. A return value is clearer there.

P8 · Building blocks: reach for these first

Need Use Not

a path

pathlib.Path

string concatenation, os.path.join chains

a fixed set of values

enum.Enum or StrEnum

bare strings compared everywhere

a value object

@dataclass(frozen=True)

a dict passed between functions

a record from JSON

TypedDict, or a dataclass and a parser

dict[str, Any]

resource lifetime

with or contextlib.contextmanager

manual open and close pairs

a transform

a comprehension

map or filter with a lambda

counting, grouping

collections.Counter or defaultdict

hand-rolled loops

a subprocess

subprocess.run([…​], check=True, timeout=…​)

os.system, shell=True

config or data

stdlib json, csv, tomllib

a hand-written parser

a temp file

tempfile

a path in /tmp that you build yourself

A comprehension that needs a comment has stopped being a comprehension, so write the loop. More than two for clauses is that signal. Use match for structural dispatch. A dict of handlers still beats a five-arm match on a string.

P9 · Function and module discipline

Metric Cap Kind

Function length

40 lines

soft: state a reason to exceed it

Module length

400 lines

soft: beyond it, a feature is asking to split

Parameters

5, then a dataclass

soft

Nesting depth

3, then guard clauses or early return

hard

Branches per function

about 10 (ruff PLR0912)

soft

Positional arguments at a call site

3, then keyword-only

soft

Line length

100

hard (ruff enforces it)

Where the numbers come from:

  • Line length 100 is the ruff setting of the estate.

  • Five parameters, keyword-only after three, PLR0912 and the 400-line module are Python-specific. They follow from black and ruff defaults, and from modules (not classes) being the unit here.

  • Function length 40 and nesting depth 3 are the same as ft-java-standards section J16. They are not copied from it. They are language-neutral, because they follow from what a reader holds in mind.

  • The rest of the Java standard does not apply: record parameter objects, DI style, checked-exception flow and class-length caps.

Rules:

  • Use keyword-only parameters after three positional ones: def deploy(plan, *, dry_run=False, force=False). A call like deploy(plan, True, False) is unreadable, and this rule prevents it.

  • Give each module one reason to change and each function one job. A one-sentence description that contains "and" is the split point.

  • Don’t write a body that is one if/elif chain over a type. Use a dict of handlers or polymorphism.

P10 · Tests

Use pytest. Mirror the package layout and name files test_*.py. New or changed code has at least 80% diff coverage, measured with coverage.py and diff-cover. The test taxonomy of the agent platform is the model. Each kind answers a different question.

Kind Answers

unit

Does this decision hold, with no I/O?

integration

Do the parts agree once wired?

contract

Does the payload still match what the other side expects?

property

Does the invariant hold across generated inputs (hypothesis)?

fault

What happens when the dependency fails, times out or half-succeeds?

migration

Does the schema change apply, and apply twice?

  • Write the test first on non-trivial logic: red for the right reason, green, refactor. A test that never failed proves nothing.

  • Name tests after the behavior: test_resolve_targets_skips_offline_devices. Don’t use test_1 or test_service.

  • Separate Arrange, Act and Assert visibly.

  • Use pytest.mark.parametrize for one behavior over many inputs. Don’t loop inside one test, because the first failure hides the rest.

  • Use tmp_path, monkeypatch, caplog and fixtures. Don’t use mock.patch on the subject under test. Mock the boundary (HTTP, clock, filesystem), never the thing you test.

  • Don’t use time.sleep, a real network call, or a test that depends on the leftovers of another test.

  • Every bug fix ships the test that fails without the fix. That stops the bug from returning.

  • Write property tests where an invariant exists (round-trip, idempotence, ordering). hypothesis finds the input you would not have written.

  • Cover edge cases in the same pass: empty, one, many; None; the boundary; the error path; unicode; the longest realistic input.

P11 · Flask HTTP surfaces

  • Routes contain no logic. They parse, call the service and shape the response. A route body longer than about 15 lines hides business logic.

  • Validate at the edge with an explicit parser or pydantic. Never pass raw request.json into a service.

  • Use one error handler for each app. It maps the exception hierarchy of the feature to status codes, with the same body shape everywhere. Don’t return 200 with {"error": …​}.

  • Use one blueprint for each feature, registered in the app factory.

  • The wire contract between frontend and backend (envelope, error codes) is shared with ft-java-standards section J8 and ft-angular-standards. A Python service behind the same UI uses the identical envelope. Do not invent a second one. See Internal API Contract.

  • Status codes mean what they say: 400 client error, 404 absent, 409 conflict, 422 unprocessable, 500 ours.

  • Every response a person reads follows the rule module ux/user-visible-dod.md (installed by the toolkit; see Rules). An error body is user-visible work, even when a backend handler wrote it.

P12 · Subprocess, filesystem and the shell

The FT Python surface is largely tooling, so this section weighs more here than in the Java standard. The estate has zero shell=True today. Keep it at zero.

  • Use subprocess.run([…​], check=True, timeout=…​, capture_output=True, text=True) with a list, never a string. shell=True with any interpolated value is command injection and a [MUST-FIX] finding.

  • Always set a timeout. A subprocess without one is a hung tool that waits forever.

  • Check the outcome with check=True or read returncode. On failure, log returncode and the first stderr line. Never assume it worked.

  • For anything user-supplied, use pathlib, Path.resolve() and resolved.is_relative_to(base). Path traversal is the injection of the filesystem.

  • Write atomically where a partial file could be read: a temp file in the same directory, then os.replace().

  • Don’t use os.system, eval, exec or pickle.load on anything that crossed a trust boundary.

P13 · Concurrency, asyncio, timeouts

  • Never mix blocking and async in one call path. A blocking call inside async def stalls the loop. Run it with asyncio.to_thread, or make the function sync.

  • Give every network and subprocess call a timeout. Give every retry a bound and a backoff.

  • Use ThreadPoolExecutor for I/O-bound fan-out and processes for CPU-bound work. A thread pool for CPU work buys nothing under the GIL.

  • A lock owns shared mutable state across threads, or a queue replaces it. Prefer the queue.

  • Don’t run a daemon thread that does work nobody waits for and nobody logs.

P-DB · SQLAlchemy sessions, queries and route authorization

The Flask estate runs on SQLAlchemy (102 modules import it) with Flask-Login (212 references). These rules are load-bearing.

  • The request owns the session, not a function. Use one session for each request, committed or rolled back once, at the edge. A service must not commit. A service that commits cannot join a larger transaction, and a caller can no longer roll back what it started.

  • Use with session.begin(): or an explicit try/commit/except/rollback/finally close. This prevents the partial write that an un-rolled-back exception leaves.

  • Don’t use a module-level Session = sessionmaker(…​) directly in services. It is the import-time singleton that P5 forbids, and it makes every test share one connection.

  • N+1 queries are the default, not the exception. A relationship touched inside a loop issues one query for each row. Use selectinload or joinedload for the relationships you will read, and say which. Check a list endpoint that renders related objects first.

  • Bound every query that can return many rows with pagination or an explicit limit. An unbounded .all() on a growing table is a production incident with a delay fuse.

  • Filter in SQL, not in Python. [x for x in q.all() if x.active] loads the table to discard it.

  • Put authorization on the route, before the service runs: @login_required plus the concrete permission check. A route whose only protection is that the UI does not link to it is unprotected.

  • Scope the query by the identity of the caller (filter_by(owner_id=current_user.id)), not only the response. An object the caller may not see must not be loaded and then hidden.

  • Don’t build raw SQL by string interpolation, including inside text(). Bind parameters.

  • The Alembic rules follow in P14 · Dependencies and migrations.

P14 · Dependencies and migrations

  • A new dependency needs approval from the person running the session. The manifest is the decision and the lockfile is its output. Adding or bumping a dependency follows the rule module deps/dependency-change.md (installed by the toolkit; see Rules). Take the version and API from Context7 (the MCP server context7, see Claude Toolkit Reference), never from memory, and run the CVE (known vulnerability) check.

  • Prefer the standard library. A dependency for what twenty lines can do is a permanent cost for a one-time saving.

  • Don’t add a second HTTP client, YAML parser or date library next to one that is already present.

  • Alembic: keep one head. Write a real downgrade(), or state why it cannot exist. The migration must be safe to run twice. Test a data migration in tests/migration/ and do not eyeball it.

P15 · Security baseline (code level)

  • Don’t hardcode secrets, tokens or credentials, including defaults and fixtures. Read them from the environment or the secret store, and fail loudly when they are absent.

  • Don’t build SQL from strings. Use parameterised queries with every driver.

  • Don’t use pickle, yaml.load (use safe_load), eval or exec. Don’t parse untrusted XML with the standard library (use defusedxml).

  • Use secrets for anything security-bearing. random is for simulations.

  • Hash passwords with a salted KDF (argon2, bcrypt, hashlib.scrypt), never a bare digest.

  • Verify TLS. verify=False is a [MUST-FIX] finding, not a convenience.

  • The full trigger list is the rule module security.md, and it governs.

P16 · Comments and docstrings

  • Write a docstring on every public function, class and module. Use one line on what it does, then the reason when there is a non-obvious one. Follow the existing style of the repository.

  • A comment explains why. The code says what. A comment that repeats the code goes stale and then lies.

  • A comment that names a measurement, a bug or a decision earns its space, for example "bounded because a 300KB input took 20s". This is the comment class that is missing most often.

  • Don’t leave commented-out code. It is in git.

  • A comment that contradicts its code is a defect, not a nit, because the reader trusts it.

Deep references

Read these rule modules when the task touches the area. The toolkit installs them under ~/.claude/rules/; see Rules. This standard wins on conflict.

File Topic

~/.claude/rules/security/backend-security.md

the deep security reference and the self-check

~/.claude/rules/code-quality/design-principles.md

SOLID, smells, canon by language. Its numeric thresholds are Java and Angular. P9 above is the Python set.

~/.claude/rules/code-quality/convergent-change.md

the reuse check before you write, the sibling sweep after

~/.claude/rules/deps/dependency-change.md

changing a dependency

~/.claude/rules/ux/user-visible-dod.md

any string, status or error body that a person reads

Review checklist

  • pyproject.toml is the config. Ruff and mypy run clean on what you touched.

  • Layout: src/ for a package, the layered shape for a Flask tool. The domain imports no framework.

  • Public functions are annotated. No bare Any. X | None is actually handled.

  • Frozen dataclasses cross boundaries. No mutable default arguments.

  • Dependencies are passed in. No import-time side effects. Clock and filesystem are injected.

  • Logging uses %s and key=value. No f-string in a log call. No secrets.

  • Exceptions: a type for each actionable failure, a narrow try, raise …​ from err, no bare except.

  • Function at most 40 lines, nesting at most 3, at most 5 parameters, keyword-only after 3 positional, line at most 100.

  • Tests come first. Use the right kind for the question. Mock the boundary, not the subject.

  • Every bug fix carries the test that fails without it.

  • subprocess.run with a list, check=True and a timeout. No shell=True.

  • Paths are resolved and bounded. Writes are atomic where a partial read is possible.

  • SQLAlchemy: the session is owned at the edge, no service-level commit, relationships eager-loaded where read in a loop, every multi-row query bounded, queries scoped by the caller.

  • Routes: @login_required and the concrete permission check, before the service runs.

  • Alembic: one head, a downgrade or a stated reason, safe to run twice, tested.

  • Dependency change: version and API from Context7, CVE checked.

  • Security: no hardcoded secrets, no string SQL, no pickle, eval or unsafe YAML, TLS verified.

  • Docstrings on the public API. Comments say why. No commented-out code. No comment that lies.