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.
| 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 |
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 |
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 |
51 |
359, the dominant shape |
Tooling config |
none |
ruff and mypy strict, Python 3.14, line length 100 |
|
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 |
|---|---|
|
pycodestyle and pyflakes |
|
import order |
|
modern syntax |
|
bugbear (the mutable default, the loop-variable closure) |
|
simplify, comprehensions, returns |
|
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_importsoverride 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-pythonof 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
selectlist above and non-strictmypyon 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.pyis 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.pyorcommon.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 useListorOptional. -
Anyis an admission, not a type. Model the variation with aTypedDict, a union or aProtocol. Otherwise takeobjectand narrow it explicitly. -
X | Noneobliges the caller to handleNone. Annotating it and then dereferencing it unchecked is the bug the annotation looked like it prevented. -
Prefer
Protocolover 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 stricton 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 ruleB006catches it. The fix isNoneplus building inside, orfield(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
Randomand a basePath. If you needfreezegunto control time, the clock was not injected. -
In Flask, build the app in a factory (
create_app()), register blueprints there and keepcurrent_appout 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
G004catches it. Enable theGrules where the repository can take the change. -
Write
key=valuefor every identifier, so support can grep one deployment out of a day of logs:deployment_id=…,session_id=…. For a device, logserial=(the serial number, a string) anddeviceId=(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(…)insideexcept. It attaches the traceback.logger.errorthere 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 itscontextvarsbinding survivesasyncioboundaries andextra=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 |
|---|---|
|
flow |
|
a business event |
|
degraded but handled |
|
a failed operation |
|
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), thenclass PlanConflictError(DeploymentError). -
Don’t write a bare
except:. It swallowsKeyboardInterruptandSystemExit. -
Don’t write
except Exception: pass. An error that is truly ignorable still needs a comment that says why, and adebugline. -
Keep
tryblocks narrow. Wrap the call that can fail, not the twenty lines around it. -
Use
raise NewError(…) from errwhen you translate an exception. Losing the cause loses the diagnosis. -
Put clean-up in
finallyor 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 |
|
string concatenation, |
a fixed set of values |
|
bare strings compared everywhere |
a value object |
|
a dict passed between functions |
a record from JSON |
|
|
resource lifetime |
|
manual open and close pairs |
a transform |
a comprehension |
|
counting, grouping |
|
hand-rolled loops |
a subprocess |
|
|
config or data |
stdlib |
a hand-written parser |
a temp file |
|
a path in |
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 |
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,
PLR0912and 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-standardssection 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:
recordparameter 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 likedeploy(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/elifchain 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 |
|---|---|
|
Does this decision hold, with no I/O? |
|
Do the parts agree once wired? |
|
Does the payload still match what the other side expects? |
|
Does the invariant hold across generated inputs ( |
|
What happens when the dependency fails, times out or half-succeeds? |
|
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 usetest_1ortest_service. -
Separate Arrange, Act and Assert visibly.
-
Use
pytest.mark.parametrizefor one behavior over many inputs. Don’t loop inside one test, because the first failure hides the rest. -
Use
tmp_path,monkeypatch,caplogand fixtures. Don’t usemock.patchon 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).
hypothesisfinds 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.jsoninto 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
200with{"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-standardssection J8 andft-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=Truewith 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=Trueor readreturncode. On failure, logreturncodeand the first stderr line. Never assume it worked. -
For anything user-supplied, use
pathlib,Path.resolve()andresolved.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,execorpickle.loadon anything that crossed a trust boundary.
P13 · Concurrency, asyncio, timeouts
-
Never mix blocking and async in one call path. A blocking call inside
async defstalls the loop. Run it withasyncio.to_thread, or make the function sync. -
Give every network and subprocess call a timeout. Give every retry a bound and a backoff.
-
Use
ThreadPoolExecutorfor 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 explicittry/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
selectinloadorjoinedloadfor 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_requiredplus 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 servercontext7, 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 intests/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(usesafe_load),evalorexec. Don’t parse untrusted XML with the standard library (usedefusedxml). -
Use
secretsfor anything security-bearing.randomis for simulations. -
Hash passwords with a salted KDF (
argon2,bcrypt,hashlib.scrypt), never a bare digest. -
Verify TLS.
verify=Falseis 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 |
|---|---|
|
the deep security reference and the self-check |
|
SOLID, smells, canon by language. Its numeric thresholds are Java and Angular. P9 above is the Python set. |
|
the reuse check before you write, the sibling sweep after |
|
changing a dependency |
|
any string, status or error body that a person reads |
Review checklist
-
pyproject.tomlis 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 | Noneis 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
%sandkey=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.runwith a list,check=Trueand atimeout. Noshell=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_requiredand 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.