/llmctl-python:python-standardsfrom llmctl Python
Authoring conventions for Python source: typing discipline, data modelling, module and API boundaries, error handling, resource and subprocess safety, logging, and concurrency choice. ALWAYS invoke when writing, reviewing or refactoring .py files — modules, packages, tests, or the body of a script. Covers how the code reads, not how the project is tooled: uv/pyproject setup, linter and type-checker configuration, packaging, CI and migration off pip/Poetry belong to the `modern-python` skill; single-file script mechanics and PEP 723 inline metadata belong to `python-scripts`. Do not write or review Python without this skill. Keywords: python, typing, type hints, annotations, dataclass, protocol, exceptions, pathlib, asyncio, logging, subprocess, docstring, api design.
Ships in llmctl Python. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Conventions for the Python source text — what the code says, how it is shaped, and where its boundaries sit. The bar is higher than "passes review": prefer the version that makes a wrong call impossible over the version that checks for it.
Worked ✅/❌ examples live in references/ and are linked from each section — load them on demand rather than reading them all up front.
Scope boundary. This skill does not configure anything. Project bootstrap, pyproject.toml sections, uv commands, linter and type-checker configuration, dependency groups, packaging, pre-commit, CI and migration off legacy tooling are owned by the modern-python skill installed as an APM dependency of this package. The single-file script form — PEP 723 inline metadata, shebangs, exit codes, graduation to a project — is owned by python-scripts. Invoke whichever others the task spans.
Three tiers, decided by what the file is, not by how long it took to write. Every later section reads against this.
| Tier | What it is | Typing | Tests |
|---|---|---|---|
| One-off script | Single file, run directly, not imported, disposable or personal | Annotate every signature; a strict checker is optional | A pure core function that could be tested; no suite |
| Shared code | A script others run, or any module a second file imports (a utils.py included) | Strict checking strongly recommended — this is where untyped code starts costing | Tests for the logic that is now depended on |
| Project | Multi-file package or application | Strict checking required, no exemptions carved for convenience | Required, with the project's coverage floor enforced in CI |
The dangerous tier is the middle one. A file becomes shared the moment something imports it; that is when annotations and a checker stop being polish and start being the contract. Treat "this started as a script" as history, not as an exemption.
Annotate every parameter, return and public attribute. An unannotated public signature is an incomplete definition, not a style choice.
X | None, not Optional[X]. list[str]/dict[str, int], not typing.List/typing.Dict. On 3.12+, the type statement for aliases and PEP 695 syntax for generic functions and classes.Optional. A parameter defaulting to None is typed X | None explicitly.Iterable[str], Sequence[int], Mapping[str, int]); returns state the concrete type (list[str]), because the caller has to work with what comes back.Any is a defect, not a type. It disables checking for everything downstream. Use object plus narrowing, a TypeVar, a Protocol, or an overload. Where Any is genuinely unavoidable (untyped third-party surface), confine it to one adapter function and annotate the boundary.Protocol over inheritance for dependencies. A function that needs "something with .read()" declares a Protocol; it does not demand a base class the caller must inherit.Literal, Enum or Final instead of free strings and magic numbers. A parameter that accepts three strings should accept exactly three.if TYPE_CHECKING: with from __future__ import annotations where the target version needs it — keeps import graphs from growing edges that exist only for the checker.TypeIs (3.13+) rather than TypeGuard when the negative branch should narrow too; TypeGuard narrows only the positive branch and quietly leaves the else wide.@override (3.12+) on every method that overrides a base — it catches the rename that silently turns an override into a new method.# type: ignore carries a code and a reason (# type: ignore[arg-type] # upstream stub is wrong, see #123). A bare ignore is an unbounded suppression.See typing.md for ✅/❌ examples of each rule.
Make illegal states unrepresentable, then parse into that shape once at the edge.
@dataclass(frozen=True, slots=True, kw_only=True) is the default shape: immutable by default, cheap, and keyword-only so adding a field never silently reorders a call site. Reach for a plain mutable dataclass only where mutation is the point.dict[str, Any] crossing a function boundary is a missing type. It is acceptable as the immediate output of json.loads and nowhere else.NamedTuple for a positional value with no behaviour; Enum for a closed set; TypedDict only where a dict shape is forced on you by an external format.See design.md for ✅/❌ examples.
__all__ on any module meant to be imported from; a leading underscore on everything else. What is not exported can be changed freely — that is the point.See design.md for ✅/❌ examples.
def f(items: list[str] = [])). Use None and build inside, or a field(default_factory=...) on a dataclass.if; the happy path stays at the left margin.Result | None | str on different paths is three functions.map/filter with a lambda; a generator where the sequence is large or lazily consumed; a plain loop where the comprehension would need two for clauses and a condition to stay readable.zip(..., strict=True) whenever the inputs are expected to be the same length — the default silently truncates to the shortest.enumerate instead of maintaining an index; pathlib instead of string path arithmetic.match for dispatch on structure, not as a substitute for an if/elif chain on one value.render(data, strict=True), never render(data, True).except: (it swallows KeyboardInterrupt and SystemExit), and never except Exception: pass. contextlib.suppress(SpecificError) when ignoring is genuinely correct — it states which error is being ignored.raise NewError(...) from err. Re-raising without from discards the traceback that explains what actually happened.f"config key {key!r} missing from {path}", not "invalid config". An error that cannot be acted on is a bug report the user has to write for you.try block wraps the one call that can fail, not the twenty lines around it.See runtime.md for ✅/❌ examples.
with. Files, sockets, locks, pools, temporary directories. Write your own contextlib.contextmanager when a resource has a lifecycle.encoding= is always explicit on open() and on any text conversion. The platform default is not the same on every machine, which is exactly the class of bug that only appears in production.pathlib.Path throughout; os.path string handling only when an API forces it.subprocess.run with an argument list and check=True. Never shell=True with an interpolated string — that is a command-injection primitive. Capture output explicitly rather than letting it leak into the parent's streams.tempfile for scratch space, never a hardcoded /tmp/... path.datetime.now() or reads os.environ in its core cannot be tested without patching. Pass the value in.See runtime.md for ✅/❌ examples.
logger = logging.getLogger(__name__) at module level; never print in importable code. print writes to a stream the caller did not choose and cannot filter.logger.info("loaded %d rows from %s", n, path). An f-string is formatted even when the level is disabled.basicConfig, no handler installation, no level setting outside the application entry point.logger.exception(...) inside an except block — it attaches the traceback; logger.error(str(err)) throws it away.Pick the model from the workload, and do not mix models inside one boundary.
asyncio with structured concurrency: asyncio.TaskGroup (3.11+), not a bare list of create_task calls that nobody awaits. asyncio.timeout for deadlines.concurrent.futures.ThreadPoolExecutor.ProcessPoolExecutor. Threads will not help under the GIL; free-threaded builds exist but are not the default, so do not assume them.asyncio.to_thread it, or the event loop stalls for every other task.See runtime.md for ✅/❌ examples.
Args/Returns/Raises only where the signature does not already say it. Never restate the types — the annotations carry them.TODO without an owner or issue.timeout_seconds, not timeout; is_expired, not flag; user_ids, not data. No abbreviations beyond the universally known ones.eval, exec, or pickle.loads on input you did not produce.secrets, never random, for tokens, keys and anything an attacker should not predict.Target the oldest version actually supported, and say so in one place (requires-python). New work with no constraint targets the current stable release. Do not carry compatibility shims for versions that have reached end of life — dropping them is a feature, not a regression. Where a rule above names a version (PEP 695 syntax on 3.12+, TypeIs on 3.13+), apply it only when the floor allows; otherwise use the older equivalent rather than a conditional import.
Before calling Python work finished:
Any; no implicit Optional# type: ignore carries a code and a reason__all__ set, or everything internal underscoredfrom, with the offending value in the messageexcept, no silent pass, no log-and-re-raise chainswith; every open() has encoding=subprocess calls pass a list and check=True; no shell=True on interpolated inputprint in importable code; no logging configuration in a libraryeval/exec/pickle on untrusted input, no string-built queriesFollow the repository's existing convention. If a project already runs black, flake8, pylint or isort, use it and do not migrate it as a side effect of unrelated work. A consistent codebase beats a fashionable one.
Where a project has no convention — a new project, or one with nothing configured — use ruff for both formatting and linting, and let the modern-python skill configure it. Neither tool is mandated by this skill: none of the rules above depend on which linter runs, and a formatter cannot produce any of the properties in §1–§11.
modern-python skill (APM dependency): uv, pyproject.toml, ruff/ty configuration, dependency groups, CI, migrationpython-scripts: PEP 723 inline metadata, shebangs, exit codes, graduation criteriaWhat SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub siegenthalerroger/.llmctl-marketplace --plugin llmctl-python3 skills in this plugin
/modern-pythonConfigures Python projects with modern tooling (uv, ruff, ty). Use when creating projects, writing standalone scripts, or migrating from pip/Poetry/mypy/black./python-scriptsSingle-file Python script discipline: PEP 723 inline script metadata as the only way a script declares its dependencies, an executable shebang, locking for reproducibility, argument/stream/exit-code conventions, and the criteria for graduating a script into a project. ALWAYS invoke before creating or editing a standalone .py file that is run rather than imported — automation, a one-off, a tool, a CI helper. Do not write a script that assumes pre-installed packages, ships a sidecar requirements.txt, or tells the user to install anything globally. Runner-agnostic: uv is the default, but any PEP 723-aware runner satisfies the rule. Conventions for the code inside the script belong to `python-standards`; multi-file project tooling to `modern-python`. Keywords: script, standalone, one-off, automation, shebang, PEP 723, inline metadata, uv run, pipx, cli, argparse, exit code.Other plugins' skills for the same job