agentleFS
leroyguillaumeleroyguillaume/skills/python-conventions/SKILL.md

python-conventions

Skill7 starsChanged 2 days agoMITView on GitHub

Python projects: uv, ruff, typer, pydantic, Pylance, test coverage. TRIGGER when: editing or creating `.py` files; touching `pyproject.toml`, `uv.lock` or `.python-version`; adding a Python dependency; setting up a Python CLI, config layer or data model; measuring test coverage; user asks about Python tooling, types or env vars. SKIP when: no Python is involved. Load `python-async-conventions` alongside for asyncio loops.

9 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

12 rules. 0 are common, 1 is distinctive, and 11 are very specific to this project.

  • 0

    Common

    Most of the 8 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 11

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use pyproject.toml as the single source of truth for metadata, dependencies, and tool configuration (ruff, pytest, etc.).

    line 30
  2. Very specific:

    Use uv for dependency and environment management: uv init, uv add, uv sync, uv run, uv lock.

    line 32
  3. Very specific:

    Add astral-sh/ruff-pre-commit to .pre-commit-config.yaml with both ruff-check and ruff-format hooks.

    line 38
  4. Distinctive:

    When pyright and ruff disagree on a stylistic point, prefer the change that satisfies both.

    line 54
  5. Very specific:

    Never use pip, poetry, pipenv, or conda.

    line 153
  6. Very specific:

    Never create a setup.py, setup.cfg, requirements.txt, ruff.toml, or pytest.ini.

    line 154
  7. Very specific:

    Never hand-edit dependency files.

    line 156
  8. Very specific:

    Never read config via os.environ.get(...) scattered through the code.

    line 157
  9. Very specific:

    Never declare typer parameters with the legacy param: T = typer.Option(default, ...) form.

    line 159
  10. Very specific:

    Never silence a Pylance / pyright diagnostic with # type: ignore, # pyright: ignore, or cast() without a one-line comment explaining why …

    line 161
  11. Very specific:

    Never pass a dict[str, Any] (or a positional tuple) between functions as a stand-in for a record whose fields are known, and never annotate …

    line 165
  12. Very specific:

    Never use print() for diagnostics.

    line 169

“Common” is measured: kept by at least 6 in 10 of the 8 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Python conventions

Always:

  • Name every variable, function, method, attribute, and model field in snake_case (PEP 8). This holds for Pydantic models too — never declare literal camelCase field names. When a model serialises to a wire format that wants camelCase (a Kubernetes CRD, a camelCase JSON API), keep the Python fields snake_case and let an alias bridge the gap: set alias_generator=to_camel, validate_by_name=True and serialize_by_alias=True on the base model's ConfigDict (Pydantic ≥ 2.11; populate_by_name is discouraged there), so endpoint_url becomes endpointUrl on the wire while Python stays idiomatic, and either spelling is accepted on the way in. Keep ruff's N815 (mixed-case class variable) enabled — it is the guard that catches a stray camelCase field. Ruff's default rule set does not include pep8-naming, so select must list "N", and N815 never goes in ignore.
  • Use pyproject.toml as the single source of truth for metadata, dependencies, and tool configuration (ruff, pytest, etc.).
  • Use uv for dependency and environment management: uv init, uv add, uv sync, uv run, uv lock. Commit uv.lock.
  • Pin Python and uv in mise.toml, never in a .python-version (mise-conventions).
  • Format and lint with ruff (ruff format + ruff check --fix). Configure in pyproject.toml.
  • Add astral-sh/ruff-pre-commit to .pre-commit-config.yaml with both ruff-check and ruff-format hooks.
  • Type-check with pyright as a blocking pre-commit hook, on the same footing as ruff: RobertCraigie/pyright-python, hook id pyright, the wrapper pyright's own docs point to. Pylance runs pyright, so it is the editor view of the same diagnostics, not a separate gate. The hook runs in its own virtualenv, so point pyright at the project's in pyproject.toml, or every third-party import is unresolved:

    [tool.pyright]
    venvPath = "."
    venv = ".venv"

    Fix every reported error and warning before considering a change done. When pyright and ruff disagree on a stylistic point, prefer the change that satisfies both; never silence one to keep the other happy.

  • Measure test coverage with coverage.py through pytest-cov (ci-conventions): coverage.py is the reference tool, and the plugin runs it from the pytest call contributors already make, pytest-xdist workers included. It is a dev dependency (uv add --dev pytest-cov), so uv.lock pins it, not mise.toml. Branch coverage is free here, so on:

    [tool.coverage.run]
    branch = true
    source = ["<package>"]
      coverage:
        desc: Run the tests and measure their line and branch coverage
        cmds:
          - uv run pytest --cov --cov-report=term --cov-report=html {{.CLI_ARGS}}
    
      coverage:summary:
        desc: Print the summary of the last coverage run
        cmds:
          - uv run coverage report

    The HTML report lands in htmlcov/; gitignore it with .coverage and coverage.xml. On GitLab, add --cov-report=xml (Cobertura, in coverage.xml); the job's regex is /^TOTAL.*\s(\d+(?:\.\d+)?)%/.

  • Build CLIs with typer, every option carrying its envvar=..., or use pydantic-settings for richer config models (env_prefix="mytool_" for a CLI). Precedence and variable names follow config-conventions.
  • Declare typer parameters with Annotated[T, typer.Option(...)] = default, not param: T = typer.Option(default, ...). The Annotated form keeps the default value in the standard Python position and is the form typer recommends. Example:
    from pathlib import Path
    from typing import Annotated
    import typer
    
    def sync(
        config_file: Annotated[
            Path, typer.Option(envvar="MYTOOL_CONFIG_FILE", help="Config file")
        ] = Path("mytool.toml"),
    ) -> None: ...
  • Apply logging-conventions. Python mechanics: use the standard logging module (or structlog when the project already does), configured once at process start; the level and the format are options of the typer / pydantic-settings config layer (names in config-conventions and logging-conventions), the format choosing the formatter. Log structured key-values (logger.debug("fetched", extra={"url": url, "status": resp.status})), never f-string interpolation of values into the message. The default logging formatter silently drops extra= fields, so install a structured (JSON or key=value) formatter that renders them; and an extra key that clashes with a LogRecord attribute (name, message, module, …) raises KeyError.
  • In a long-running process, apply signal-handling-conventions. Python mechanics: Python's default SIGTERM action kills the process with no cleanup, and KeyboardInterrupt only covers SIGINT. In asyncio, register both on the running loop and drive shutdown from one event:
    stop = asyncio.Event()
    loop = asyncio.get_running_loop()
    for sig in (signal.SIGTERM, signal.SIGINT):
        loop.add_signal_handler(sig, stop.set)
    A server or worker loop then exits once stop is set, after draining. A synchronous loop installs signal.signal for both and checks a flag between units of work. add_signal_handler is unix-only, which is the right default for a Linux-container target.
  • Model structured data with an explicit type, never a bare dict / tuple threaded through the code as an ad-hoc record. As soon as a value has a known, fixed set of fields:

    • First, reuse the canonical type if one already exists in the standard library or a dependency you already have (e.g. kubernetes.client.V1OwnerReference, an SDK's request/response model, a protobuf/dataclass the API ships). Do not hand-roll a parallel model of something a depended-upon library already defines — convert at the edges with the library's own serializer (ApiClient().sanitize_for_serialization, .model_dump(), …). A request or response body your own API exposes is the exception: it gets a DTO of its own (api-conventions).
    • Otherwise define one: a pydantic.BaseModel when it crosses an I/O, serialization, or API boundary (parsed from / rendered to JSON, YAML, a request, a manifest, …) — the default in a Pydantic codebase; a @dataclass(frozen=True) for an internal value object that never leaves the process; a TypedDict only when an external API hands you a dict you do not construct yourself and a model wrapper would be pure overhead.

    Reserve dict[...] / Mapping for genuinely dynamic maps whose keys are data, not field names. Construct the type at the boundary where the data enters and pass the typed object onward; do not pass the raw dict.

Never:

  • Never use pip, poetry, pipenv, or conda.
  • Never create a setup.py, setup.cfg, requirements.txt, ruff.toml, or pytest.ini. All config lives in pyproject.toml.
  • Never hand-edit dependency files; use uv add / uv remove.
  • Never read config via os.environ.get(...) scattered through the code; route everything through the typer / pydantic-settings layer.
  • Never declare typer parameters with the legacy param: T = typer.Option(default, ...) form; use Annotated instead.
  • Never silence a Pylance / pyright diagnostic with # type: ignore, # pyright: ignore, or cast() without a one-line comment explaining why the type checker is wrong and why the cast is safe. If you can fix the underlying type instead, do that.
  • Never pass a dict[str, Any] (or a positional tuple) between functions as a stand-in for a record whose fields are known, and never annotate a parameter or return as a broad dict / tuple when the shape is fixed and knowable — define the type and use it.
  • Never use print() for diagnostics; route everything through the configured logger.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.