Skip to content

Python Project Tooling: uv, Virtual Environments, Ruff, pyproject, Dependency Locking ​

"A virtual environment is created on top of an existing Python installation, known as the virtual environment's "base" Python, and by default is isolated from the packages in the base environment, so that only those explicitly installed in the virtual environment are available." — Python documentation, venv module, docs.python.org/3/library/venv.html

Summary: A Python project is four decisions made once: which interpreter (CPython from python.org, a distro, pyenv or a uv-managed build), which isolated environment holds its packages (a virtual environment, .venv), where its requirements are declared (pyproject.toml: PEP 621 metadata, extras, PEP 735 dependency groups, tool tables) and how the exact versions are frozen (a lockfile: uv.lock, or a hashed requirements.txt). uv does all four from one binary (uv init, uv add, uv lock, uv sync, uv run, uv python, uvx), Ruff replaces the linter, the import sorter and the formatter, and the same two files drive the Dockerfile and the CI job. Focus: interpreters and python3 vs python (PEP 394), why virtual environments exist (site-packages, sys.path, pyvenv.cfg, python -I), venv vs virtualenv vs uv venv, pyproject.toml ([build-system], [project], extras, dependency groups, [tool.*]), version specifiers (PEP 440) and environment markers (PEP 508), uv's project commands, scripts with inline metadata (PEP 723), the uv cache, uv pip, workspaces, lockfiles and uv export, pip / pip-tools / Poetry / PDM / Rye / Hatch compared, Ruff (ruff check, ruff format, rule selection, isort and pyupgrade rules, per-file ignores, Black compatibility, pre-commit), mypy and pyright as a preview, pytest as a tool, task runners (uv run, Makefile, justfile), uv in Docker (multi-stage, --no-dev, UV_COMPILE_BYTECODE), CI with setup-uv, src vs flat layout, .env files, and the Composer and Go-modules comparisons. Learning goal: Create a Python project from nothing and be able to say, for every file and command, what it is for: pin an interpreter, create and recreate the environment from the lock in one command, add and remove dependencies without editing the environment by hand, keep production images free of test tools, fail CI when the lock is stale, and lint and format with one fast tool configured in pyproject.toml.

This is the first chapter of the Python section, so it also orients a Laravel or Go developer: where Composer's composer.json / composer.lock / vendor/ and Go's go.mod / go.sum / module cache land in Python, and why Python needs one extra concept (the virtual environment) that neither of them has. It does not re-teach its neighbours: type hints and Pydantic are in Typing & Pydantic v2; the event loop is in Async Python; the first FastAPI application, whose pinned pyproject.toml is the model for ours, is in FastAPI Fundamentals; how a service is split into packages is in APIRouter & Project Structure; pytest for FastAPI is in Testing FastAPI; running the finished service is in FastAPI in Production; the image and pipeline mechanics are in Images & Dockerfiles and CI/CD Pipelines; Git itself is in Git & Version Control; the Go twins are Toolchain, Modules & Packages and Project Layout, golangci-lint, Makefile, Docker & Multi-Binary Builds.

Version note (2026-11-29)

The page targets Python 3.12 / 3.13 and uv 0.13.x. Everything marked real run was executed on this machine on 2026-11-29 with CPython 3.9.6 (the only interpreter installed), uv 0.13.10 (pip install --user uv, outside the repository), Ruff 0.17.6, mypy 1.19.1, pytest 8.4.2 and packaging 26.3; the transcripts are in pipeline/sources/python-tooling-uv-ruff-venv/runs/. Because the lock was resolved with requires-python = ">=3.9", it shows uv choosing different versions for 3.9, 3.10 and 3.11+ (fastapi 0.128.8, 0.162.5, 0.165.0). Marked expected, not run: uv python install (downloads an interpreter), the installer scripts, pyenv, Docker builds, GitHub Actions, pre-commit install, Windows commands, Composer and Go commands.

Page map ​

If you are looking forGo to
The tables you can memorise in one minuteEverything in one minute
Why Python projects need this much toolingWhy it exists
Python 2 to uv: a timelineWhere it comes from
The snippet project, before and afterPython
Which python, python3, which versionInterpreters
What a virtual environment really isVirtual environments
venv, virtualenv, uv venvvenv vs virtualenv vs uv venv
[project], extras, groups, [tool.*]pyproject.toml
>=, ~=, ==, markersVersion specifiers and markers
uv init, uv add, uv sync, uv runuv projects
uv python install, .python-versionuv python
uvx, uv toolTools: uvx
A single file with its own dependenciesInline script metadata
uv pip install, uv pip compileThe pip interface
Several packages in one repositoryWorkspaces
Why uv is fast, where packages are storedThe cache
uv.lock, requirements.txt, hashesLockfiles
pip, pip-tools, Poetry, PDM, Rye, HatchChoosing a tool
ruff check, rule codes, ruff formatRuff
pre-commit, Black compatibilityRuff in the workflow
mypy and pyrightType checking preview
pytest, Makefile, justfileTests and tasks
src/ or flatProject layout
.env, python-dotenv, pydantic-settingsConfiguration and .env
Dockerfile with uvDocker
GitHub Actions with uvCI
Exact messages and commandsMechanics
Composer, Pint, go.mod, gofmtFor PHP/Laravel developers, The Go angle

Everything in one minute ​

The four layers. Each row is unpacked in the concept catalogue.

LayerWhat it isPlain wordsWhere it lives
InterpreterCPython (or PyPy …) at a version"The program that runs .py files"/usr/bin/python3, python.org installer, pyenv shim, uv-managed build
EnvironmentA directory with its own site-packages and a pyvenv.cfg"A private shelf of libraries for one project".venv/ next to pyproject.toml
Declarationpyproject.toml"What the project wants: ranges, extras, groups, tool settings"repository root
Lockuv.lock or hashed requirements.txt"What was actually chosen: exact versions, hashes, markers"repository root, committed

The commands you will type daily.

CommandDoesEdits
uv initCreates pyproject.toml, .python-version, src/<name>/files
uv add httpx / uv remove httpxEdits [project] dependencies, re-locks, syncspyproject.toml, uv.lock, .venv
uv add --dev pytestAdds to the dev dependency groupsame
uv add --optional api uvicornAdds to an extrasame
uv lockRe-resolves, writes uv.lockuv.lock
uv syncMakes .venv match the lock exactly.venv
uv run <cmd>Locks and syncs if needed, runs inside .venvmaybe all three
uv python install 3.13Downloads a managed interpreteruv's data directory
uvx ruff check .Runs a tool in a temporary environmentcache only
uv exportWrites requirements.txt from the lockstdout

Ruff in one table.

ConcernCommandConfigured in
Find bugs and style problemsruff check .[tool.ruff.lint] select = ["E", "F", "I", "UP", "B"]
Fix the safe onesruff check --fix .same; unsafe fixes need --unsafe-fixes
Format (Black-style)ruff format .[tool.ruff.format], line-length
Check in CI without writingruff format --check .exit code non-zero
Sort importsrule set I (isort)[tool.ruff.lint.isort]
Modernise syntaxrule set UP (pyupgrade)target-version

Reproducibility in one table.

SituationCommandWhy
New teammateuv syncSame versions as everybody
CIuv sync --lockedFail if pyproject.toml and uv.lock disagree
Docker, deps layeruv sync --locked --no-install-project --no-devCacheable layer without test tools
Legacy deploy tooluv export --no-dev --no-emit-project > requirements.txtpip can install it with --require-hashes
Upgrade one packageuv lock --upgrade-package httpxBump only that one

Why it exists ​

Composer installs into a vendor/ directory inside each project and Go resolves modules per go.mod; a plain Python interpreter has one site-packages per installation, so by default every project on a machine shares one shelf. Two projects that need different versions of one library cannot both be satisfied by one global shelf; virtual environments, lock files and a declarative pyproject.toml are the repairs.

ProblemWhat goes wrong without the toolWhich tool answers
Two projects, two versions of a libraryOne of them breaks after pip install -UA virtual environment per project
"Works on my machine"Teammate resolves >=2 to a newer releaseA lockfile
Which Python?The distro's python3 changes with an OS upgrade.python-version, requires-python, uv python
Dev tools in productionThe image ships pytest, ruff and mypyDependency groups, --no-dev
Slow installsCI spends minutes in pip installuv's cache, a cached Docker layer
Style argumentsReviews about quotes and import orderOne formatter, one linter, in pre-commit and CI

The trade-off in one table.

SimplerMore reproducible
pip install -r requirements.txt into the global interpreterEnvironment per project, locked, hashed
Ranges only (httpx>=0.28)Exact versions in a committed lock
One requirements.txt for everything[project] for runtime, groups for development, extras for optional features
Install by hand in CIuv sync --locked, cached by uv.lock

The analogy used through the page. A kitchen. The interpreter is the stove, the virtual environment is a lunchbox of ingredients packed for one dish, pyproject.toml is the recipe ("some butter, a bit of flour"), and the lockfile is the shopping receipt ("250 g of this brand, batch 7"). Two cooks with the same recipe may buy different butter; with the same receipt they buy the same one.

Three common misunderstandings, up front ​

  1. "A virtual environment is a copy of Python." It is a directory with a pyvenv.cfg that points at the base interpreter, a private site-packages, and a python that is usually a symlink to the base one. The real run below shows home = /Library/Developer/CommandLineTools/usr/bin.
  2. "pyproject.toml pins my versions." It declares ranges. Without a lock, the next pip install . can resolve to different versions; the lockfile is what pins.
  3. "uv is just a faster pip." It also creates environments, installs and selects interpreters, runs tools, locks across platforms and runs scripts with inline dependencies; the pip-compatible layer (uv pip) is one part of it, and Astral documents that it is not always identical to pip's behaviour.

Where it comes from ​

1  2011-03   PEP 394 created: python2 and python3 commands on Unix-like systems
2  3.3       Python 3.3 adds the venv module to the standard library ("Added in version 3.3")
3  2013-03   PEP 440 created: version identification and dependency specification
4  2015-11   PEP 508 created: dependency specifiers and environment markers
5  2015-16   PEP 517 (build backends, 2015-09) and PEP 518 (pyproject.toml build-system, 2016-05)
6  2020-06   PEP 621 created: [project] metadata in pyproject.toml
7  2023-08   PEP 723 created: inline script metadata
8  2023-11   PEP 735 created: dependency groups (not included in any built distribution)
9  2024-07   PEP 751 created: pylock.toml, a standard lock format (uv.lock stays uv-specific)
10 2025-02   Rye: "no longer developed as of February 2025"; uv is its successor
11 2026-11   this page: uv 0.13.10, Ruff 0.17.6 (versions real-run on 2026-11-29)

The dates are the "Created" fields of the PEPs (saved as pep-*.txt) and the "Added in version 3.3" note of the venv documentation. The Rye row is quoted from its documentation (rye-docs.txt): "Rye is no longer developed as of February 2025. Please see the guide on migrating to uv." The pylock.toml row is from the uv layout page: "In PEP 751, Python standardized a new resolution file format, pylock.toml", and the same page says the uv.lock format "is specific to uv and not usable by other tools". The release dates of virtualenv, pip, uv and Ruff are deliberately not stated: they were not fetched.

Python ​

Before ​

A "before" is not code, it is a state many projects start in: pip install fastapi into whatever python3 is first on PATH, a hand-edited requirements.txt with fastapi and nothing else, no lock, no interpreter pin, black, flake8 and isort installed three different ways. The messy file below is the lint version of that state; it is excluded from the project's own ruff check . (extend-exclude = ["lint_demo"]) and linted on purpose in the lab.

py
import sys, os
from typing import Optional, List
import json


def load(path: Optional[str] = None, seen: List[str] = []):
    if path == None:
        return seen
    try:
        data = json.load(open(path))
    except:
        data = {}
    seen.append(path)
    return {"path":path,   "data": data,"items":[ str(x) for x in range(3) ]}

After ​

The snippet project inventory-tool: a src layout, a SQLite report whose SQL is the only "business logic", a settings loader that reads .env, and tests that run with plain pip as well as with uv. The project file is the centre of the chapter:

toml
[build-system]
requires = ["hatchling>=1.27"]
build-backend = "hatchling.build"

[project]
name = "inventory-tool"
version = "0.1.0"
description = "A tiny SQLite stock report, used to show uv, venv and Ruff"
requires-python = ">=3.9"
dependencies = [
    "python-dotenv>=1.0,<2",
    "tomli>=2.0; python_version < '3.11'",
]

[project.optional-dependencies]
# Extras ship with the published package: pip install "inventory-tool[api]"
api = ["fastapi>=0.115,<1"]
test = ["pytest>=8,<9", "packaging>=24"]

[project.scripts]
inventory-report = "inventory.cli:main"

[dependency-groups]
# PEP 735 groups never ship: they are for developers (uv sync --group lint)
lint = ["ruff>=0.8,<1"]
types = ["mypy>=1.13,<2"]
dev = [{ include-group = "lint" }, { include-group = "types" }, "pytest>=8,<9", "packaging>=24"]

[tool.hatch.build.targets.wheel]
packages = ["src/inventory"]

[tool.uv]
default-groups = ["dev"]

[tool.ruff]
line-length = 88
target-version = "py39"
src = ["src", "tests"]
extend-exclude = ["lint_demo"]  # the deliberately messy demo file

[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
ignore = ["E501"]

[tool.ruff.lint.per-file-ignores]
"tests/**" = ["B011"]

[tool.ruff.format]
quote-style = "double"

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-p no:cacheprovider"

[tool.mypy]
python_version = "3.9"
strict = true
files = ["src"]

The package, standard library only except python-dotenv:

py
"""SQLite access with the standard library only."""

from __future__ import annotations

import sqlite3

SCHEMA = """
CREATE TABLE IF NOT EXISTS products (
    id       INTEGER PRIMARY KEY,
    sku      TEXT    NOT NULL UNIQUE,
    name     TEXT    NOT NULL,
    quantity INTEGER NOT NULL CHECK (quantity >= 0)
);
"""

SEED = [
    ("BK-001", "The Pragmatic Programmer", 12),
    ("BK-002", "Designing Data-Intensive Applications", 3),
    ("GM-001", "Catan", 0),
    ("MU-001", "Kind of Blue (vinyl)", 7),
]

LOW_STOCK_SQL = """
SELECT sku, name, quantity
FROM products
WHERE quantity < :threshold
ORDER BY quantity, sku;
"""


def connect(path: str) -> sqlite3.Connection:
    conn = sqlite3.connect(path)
    conn.row_factory = sqlite3.Row
    return conn


def init_db(conn: sqlite3.Connection) -> None:
    conn.executescript(SCHEMA)
    conn.executemany(
        "INSERT OR IGNORE INTO products (sku, name, quantity) VALUES (?, ?, ?)",
        SEED,
    )
    conn.commit()


def low_stock(conn: sqlite3.Connection, threshold: int) -> list[sqlite3.Row]:
    return list(conn.execute(LOW_STOCK_SQL, {"threshold": threshold}))
py
"""Configuration: real environment variables win over a .env file."""

from __future__ import annotations

import os
from dataclasses import dataclass
from pathlib import Path

from dotenv import dotenv_values


@dataclass(frozen=True)
class Settings:
    database_path: str
    low_stock_threshold: int


def load_settings(env_file: str | Path | None = ".env") -> Settings:
    """Read `.env` (if present), then let os.environ override it.

    python-dotenv's `dotenv_values` returns a dict and touches nothing in
    os.environ, so tests stay isolated.
    """
    file_values = dotenv_values(env_file) if env_file else {}
    merged = {**file_values, **os.environ}
    return Settings(
        database_path=merged.get("INVENTORY_DB", ":memory:") or ":memory:",
        low_stock_threshold=int(merged.get("LOW_STOCK_THRESHOLD", "5") or "5"),
    )
py
"""`inventory-report`: print the products below the low-stock threshold."""

from __future__ import annotations

import sqlite3
import sys
from collections.abc import Sequence

from inventory.config import load_settings
from inventory.db import connect, init_db, low_stock


def render(rows: Sequence[sqlite3.Row]) -> str:
    lines = ["sku      qty  name"]
    for row in rows:
        lines.append(f"{row['sku']:<8} {row['quantity']:>3}  {row['name']}")
    return "\n".join(lines)


def main(argv: Sequence[str] | None = None) -> int:
    args = list(sys.argv[1:] if argv is None else argv)
    settings = load_settings(None if "--no-env-file" in args else ".env")
    conn = connect(settings.database_path)
    init_db(conn)
    rows = low_stock(conn, settings.low_stock_threshold)
    print(render(rows))
    print(f"-- {len(rows)} product(s) below {settings.low_stock_threshold}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

The SQL it sends to SQLite, as a reader would run it in the sqlite3 shell:

sql
-- schema (db.py: SCHEMA)
CREATE TABLE IF NOT EXISTS products (
    id       INTEGER PRIMARY KEY,
    sku      TEXT    NOT NULL UNIQUE,
    name     TEXT    NOT NULL,
    quantity INTEGER NOT NULL CHECK (quantity >= 0)
);

-- the report (db.py: LOW_STOCK_SQL); :threshold is a bound parameter, never string-formatted
SELECT sku, name, quantity
FROM products
WHERE quantity < :threshold
ORDER BY quantity, sku;

The tests assert behaviour and also make the packaging rules executable (PEP 440 ordering, markers, extras, venv layout, python -I):

py
from __future__ import annotations

import sqlite3

import pytest

from inventory.db import connect, init_db, low_stock


@pytest.fixture
def conn() -> sqlite3.Connection:
    c = connect(":memory:")
    init_db(c)
    return c


def test_init_is_idempotent(conn: sqlite3.Connection) -> None:
    init_db(conn)
    assert conn.execute("SELECT count(*) FROM products").fetchone()[0] == 4


def test_low_stock_orders_by_quantity_then_sku(conn: sqlite3.Connection) -> None:
    rows = low_stock(conn, 5)
    assert [(r["sku"], r["quantity"]) for r in rows] == [("GM-001", 0), ("BK-002", 3)]


def test_threshold_is_a_bound_parameter(conn: sqlite3.Connection) -> None:
    assert low_stock(conn, 0) == []
    assert len(low_stock(conn, 100)) == 4


class _NoFormat(int):
    """An int that refuses to be turned into text: string interpolation would raise."""

    def __format__(self, spec: str) -> str:
        raise AssertionError("threshold was interpolated into the SQL")

    __str__ = __repr__ = __format__  # type: ignore[assignment]


def test_threshold_is_never_formatted_into_the_sql(conn: sqlite3.Connection) -> None:
    # sqlite3 binds an int subclass natively; an f-string or % implementation would raise.
    assert len(low_stock(conn, _NoFormat(5))) == 2


def test_check_constraint_blocks_negative_stock(conn: sqlite3.Connection) -> None:
    with pytest.raises(sqlite3.IntegrityError):
        conn.execute("UPDATE products SET quantity = -1 WHERE sku = 'BK-001'")
py
from __future__ import annotations

from pathlib import Path

import pytest

from inventory.cli import main
from inventory.config import load_settings


def test_report_output(capsys: pytest.CaptureFixture[str]) -> None:
    assert main(["--no-env-file"]) == 0
    out = capsys.readouterr().out
    assert out.splitlines()[0] == "sku      qty  name"
    assert "GM-001" in out and "BK-001" not in out
    assert out.rstrip().endswith("-- 2 product(s) below 5")


def test_env_file_is_read(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delenv("LOW_STOCK_THRESHOLD", raising=False)
    monkeypatch.delenv("INVENTORY_DB", raising=False)
    env = tmp_path / ".env"
    env.write_text("LOW_STOCK_THRESHOLD=9\nINVENTORY_DB=x.sqlite3\n")
    s = load_settings(env)
    assert (s.low_stock_threshold, s.database_path) == (9, "x.sqlite3")


def test_real_environment_beats_env_file(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    env = tmp_path / ".env"
    env.write_text("LOW_STOCK_THRESHOLD=9\n")
    monkeypatch.setenv("LOW_STOCK_THRESHOLD", "2")
    assert load_settings(env).low_stock_threshold == 2


def test_missing_env_file_uses_defaults(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    monkeypatch.delenv("LOW_STOCK_THRESHOLD", raising=False)
    monkeypatch.delenv("INVENTORY_DB", raising=False)
    s = load_settings(tmp_path / "nope.env")
    assert (s.low_stock_threshold, s.database_path) == (5, ":memory:")
py
"""Tests that make the venv and packaging rules executable."""

from __future__ import annotations

import subprocess
import sys
import venv
from pathlib import Path

import pytest
from packaging.markers import InvalidMarker, Marker
from packaging.requirements import Requirement
from packaging.specifiers import SpecifierSet
from packaging.version import Version


def test_tests_run_inside_a_venv() -> None:
    # Inside a venv, sys.prefix is the venv and sys.base_prefix the interpreter's home.
    assert sys.prefix != sys.base_prefix


def test_venv_layout_and_pyvenv_cfg(tmp_path: Path) -> None:
    target = tmp_path / "v"
    venv.create(target, with_pip=False)
    cfg = (target / "pyvenv.cfg").read_text()
    assert "include-system-site-packages = false" in cfg
    assert (target / ("Scripts" if sys.platform == "win32" else "bin")).is_dir()
    assert any((target / "lib").glob("python3*/site-packages"))


def test_isolated_mode_ignores_environment_and_user_site() -> None:
    code = "import sys; print(sys.flags.isolated, sys.flags.ignore_environment)"
    out = subprocess.run(
        [sys.executable, "-I", "-c", code],
        capture_output=True,
        text=True,
        env={"PYTHONPATH": "/nonexistent"},
        check=True,
    ).stdout
    assert out.split() == ["1", "1"]


def test_pep440_ordering() -> None:
    assert Version("1.0.dev1") < Version("1.0a1") < Version("1.0rc1") < Version("1.0")
    assert Version("1.0") < Version("1.0.post1")
    assert Version("1.0") == Version("1.0.0")


def test_filter_skips_prereleases_unless_asked() -> None:
    spec = SpecifierSet(">=1.0")
    # filter() is what installers use: a pre-release is only picked if nothing else fits
    assert list(spec.filter(["1.5", "2.0a1"])) == ["1.5"]
    assert list(spec.filter(["2.0a1"])) == ["2.0a1"]  # ...or the only candidate
    assert list(spec.filter(["1.5", "2.0a1"], prereleases=True)) == ["1.5", "2.0a1"]


def test_compatible_release_is_tilde_equals_not_npm_tilde() -> None:
    assert Version("1.4.9") in SpecifierSet("~=1.4.2")
    # ~=1.4.2 means >=1.4.2, ==1.4.*   and   ~=1.4 means >=1.4, ==1.*
    assert Version("1.5.0") not in SpecifierSet("~=1.4.2")
    assert Version("1.9.0") in SpecifierSet("~=1.4")


def test_environment_markers() -> None:
    m = Marker("python_version < '3.11'")
    assert m.evaluate({"python_version": "3.9"})
    assert not m.evaluate({"python_version": "3.12"})
    req = Requirement("tomli>=2.0; python_version < '3.11'")
    assert req.name == "tomli" and str(req.specifier) == ">=2.0"
    assert req.marker is not None


def test_extras_are_part_of_the_requirement_string() -> None:
    req = Requirement("inventory-tool[api,test]>=0.1")
    assert req.extras == {"api", "test"}


def test_unknown_marker_variable_is_rejected() -> None:
    with pytest.raises(InvalidMarker):
        Marker("not_a_marker_var == '1'")

A single file with PEP 723 inline metadata, for scripts that live outside a project:

py
# /// script
# requires-python = ">=3.9"
# dependencies = ["python-dotenv>=1.0"]
# ///
"""A single-file script with PEP 723 inline metadata (run with `uv run`)."""

import sys

import dotenv

print("executable :", sys.executable)
print("prefix     :", sys.prefix)
print("base_prefix:", sys.base_prefix)
print("in a venv  :", sys.prefix != sys.base_prefix)
print("dotenv from:", dotenv.__file__)

Task runners, pre-commit, Docker and CI (each explained in its section):

.PHONY: sync lint fmt test report
sync:
	uv sync
lint:
	uv run ruff check .
	uv run ruff format --check .
fmt:
	uv run ruff check --fix .
	uv run ruff format .
test:
	uv run pytest
report:
	uv run inventory-report --no-env-file
# `just` recipes: the same tasks, without Make's tab and .PHONY rules
default: lint test

sync:
    uv sync

lint:
    uv run ruff check .
    uv run ruff format --check .

test:
    uv run pytest

report:
    uv run inventory-report --no-env-file
yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.17.6
    hooks:
      - id: ruff-check   # the linter; --fix applies the safe fixes
        args: [--fix]
      - id: ruff-format  # the formatter (Black-compatible)
# syntax=docker/dockerfile:1
FROM python:3.12-slim AS builder
COPY --from=ghcr.io/astral-sh/uv:0.13.10 /uv /uvx /bin/
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=never
WORKDIR /app
# 1. Dependencies only: this layer is rebuilt only when uv.lock or pyproject.toml change
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=uv.lock,target=uv.lock \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    uv sync --locked --no-install-project --no-dev
# 2. The project itself, installed non-editable so the final image needs no source tree
COPY pyproject.toml uv.lock ./
COPY src ./src
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --locked --no-dev --no-editable

FROM python:3.12-slim
RUN useradd --create-home app
COPY --from=builder --chown=app:app /app/.venv /app/.venv
ENV PATH="/app/.venv/bin:$PATH"
USER app
CMD ["inventory-report", "--no-env-file"]
yml
name: ci
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ["3.9", "3.12", "3.13"]
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
        with:
          version: "0.13.10"
          enable-cache: true
          cache-dependency-glob: "uv.lock"
          python-version: ${{ matrix.python-version }}
      - run: uv sync --locked
      - run: uv run ruff check .
      - run: uv run ruff format --check .
      - run: uv run mypy
      - run: uv run pytest
ini
# Copy to .env (never commit .env). Real environment variables win over this file.
INVENTORY_DB=inventory.sqlite3
LOW_STOCK_THRESHOLD=5

The Python angle ​

Three Python-specific facts shape everything below. Installation is a copy, not a link to a source tree: pip install and uv sync unpack wheels into one site-packages directory, and the interpreter finds them because that directory is on sys.path; that is why "which environment am I in" is the first debugging question. Dependencies are resolved at install time against an index, not vendored: nothing in your repository records which versions were chosen unless you commit a lock. Metadata used to be code: setup.py ran arbitrary Python to say what a package needs; PEP 518/517/621 moved that into declarative TOML plus a pluggable build backend (hatchling, setuptools, uv_build ...). The src/ layout is not required by any of this, but the Python Packaging User Guide recommends thinking about it, and uv's uv init now generates it (section layout).

The concept catalogue ​

Interpreter, virtual environment, packagesBase interpreterpython3.9 (CPython)python.org, pyenv,uv-managed, systemstdlib + own site-packagesVirtual environment (.venv)pyvenv.cfg: home = base dirinclude-system-site-packages = falsebin/python (symlink to base)lib/python3.9/site-packages/site-packagespytest, ruff, dotenv ...editable project: .pthpip / uv install herenothing else sees themhome =sys.pathWhat Python computes at start-upsys.base_prefix = base interpreter home sys.prefix = the venv directory (differs inside a venv)sys.path = [script dir or "", stdlib ..., venv site-packages, .pth entries]python -I drops script dir, PYTHON* variables, user siteactivate only edits PATH and prompt: .venv/bin/python works without it

Interpreters, versions and the python command (python3 vs python) Must-know ​

In plain words: "Python" on your machine is one or more interpreter installations, each a specific version of CPython. Which one runs when you type python3 depends on your PATH; a project should say which version it needs and use an environment that points at exactly that one.

Common misunderstanding: "python and python3 are the same thing everywhere." PEP 394 says the opposite: "Some Linux distributions will not provide a python command at all by default, but will provide a python3 command by default." On this macOS machine which python python3 printed python not found and /usr/bin/python3 (real run, venv-probes.txt). Inside an activated virtual environment both exist and refer to the environment's interpreter.

Definition: An interpreter has a version (3.9.6 here), a sys.base_prefix (its installation directory) and its own standard library. Sources of interpreters, from least to most project-friendly: the operating system's (here Apple's Command Line Tools build at /usr/bin/python3, which forwards to /Library/Developer/CommandLineTools/...); installers from python.org (the downloads page lists the releases); version managers such as pyenv ("lets you easily switch between multiple versions of Python", via shims on PATH); and uv-managed builds installed with uv python install.

     You type                         Resolution
1    python3                          first python3 on PATH -> /usr/bin/python3 (3.9.6 here)
2    python                           not on PATH on a fresh Mac -> "command not found"
3    pyenv shim on PATH               pyenv picks 3.12 from .python-version or PYENV_VERSION
4    source .venv/bin/activate        PATH gets .venv/bin in front; python and python3 now mean the venv's
5    uv run python                    uv finds .venv, creates it if absent, runs its interpreter

python3 vs python in one sentence: write python3 in documentation and shebangs for system interpreters, and python only inside an activated environment or a container where you control the image.

Real scenario: A teammate has Python 3.9 from the OS and you wrote X | None annotations that need 3.10 at runtime in Pydantic models. requires-python = ">=3.10" in pyproject.toml makes the tool refuse early instead of failing at import. A CI image uses 3.12 while a laptop uses 3.13: .python-version and a CI matrix make both visible.

SourceProsConsSelected by
OS Python (/usr/bin/python3)Always thereOld (3.9.6 here), owned by the OS, may be externally managedPATH
python.org installerOfficial, several versions side by sideManual install per machinepython3.12 on PATH, or full path
pyenvPer-directory version via .python-version; compiles from sourceNeeds build dependencies; shims on PATHpyenv local 3.12
uv python installPrebuilt, fast, no compiler; managed by the same tool as the projectAnother distribution source to trust.python-version, requires-python, --python
Docker python:3.12-slimExactly the version in productionNot for local editingFROM line

Fix / how to use it: Declare requires-python = ">=3.9" (this snippet; the page recommends your real minimum) and let the tool choose. In this chapter's pyproject.toml the floor is 3.9 only because that is the interpreter that ran here; new code should target 3.12 or newer. Expected, not run: uv python install 3.13 ("By default, uv will automatically download Python versions if they cannot be found on the system", per the uv docs).

Virtual environments: site-packages, sys.path, pyvenv.cfg Must-know ​

In plain words: A virtual environment is a folder that holds the libraries for one project plus a tiny file saying which Python it belongs to. Install a package "into" it and only programs run with that folder's Python can import the package.

Common misunderstanding: "I must activate the environment before using it." The venv documentation says: "You don't specifically need to activate a virtual environment, as you can just specify the full path to that environment's Python interpreter when invoking Python." Activation only edits PATH, sets VIRTUAL_ENV and changes the prompt. uv run and .venv/bin/python work without it.

Definition: The venv module creates "lightweight virtual environments, each with their own independent set of Python packages installed in their site directories". At start-up the site machinery checks the pyvenv.cfg file of the environment: per the site documentation, "If the include-system-site-packages key exists and is set to true (case-insensitive), the system-level prefixes will be searched for site-packages, otherwise they won't." The environment's sys.prefix is its own directory while sys.base_prefix stays at the base installation (both printed in the probe below), and sys.path holds the base standard library plus the environment's lib/pythonX.Y/site-packages.

     Real probe, plain venv (venv-probes.txt)
1    sys.prefix       = <scratch>/plain
2    sys.base_prefix  = /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9
3    sys.path         = ['', .../python39.zip, .../python3.9, .../lib-dynload,
4                        <scratch>/plain/lib/python3.9/site-packages, <scratch>/pcopy/src]
5    PYTHONPATH=/tmp/x python -c ...          -> sys.path[:3] = ['', '/tmp/x', '.../python39.zip']
6    PYTHONPATH=/tmp/x python -I -c ...       -> sys.path[:3] = ['.../python39.zip', '.../python3.9', '.../lib-dynload']

Line 4 shows the editable install of the project: pip install -e . added <scratch>/pcopy/src through a .pth file. Line 6 is -I: "In isolated mode, Python does not prepend the potentially unsafe path sys._path0 to sys.path, and ignores all PYTHON* environment variables, e.g. PYTHONPATH and PYTHONHOME, that might be set." It also implies -s (no user site), which matters for scripts that must not import whatever happens to sit next to them.

Real scenario: ModuleNotFoundError: No module named 'dotenv' although pip list shows it: pip and python came from different interpreters. python -m pip always installs for the python you invoked. A cron job that runs python3 report.py uses the system interpreter, not .venv: call .venv/bin/python report.py (the console scripts in .venv/bin even have the environment's interpreter as their shebang, which the probe printed: #!<scratch>/plain/bin/python).

FactWhere to see itReal value here
Which environment am I insys.prefix != sys.base_prefixTrue in the tests (test_tests_run_inside_a_venv)
Where packages golib/python3.9/site-packagespip-21.2.4, setuptools-58.0.4 in a fresh plain venv
What the environment points atpyvenv.cfg: home, include-system-site-packages, versionhome = /Library/Developer/CommandLineTools/usr/bin
What uv venv addsuv = 0.13.10 and version_info = 3.9.6 keys; no pipsite-packages holds only _virtualenv.pth and _virtualenv.py
Which Python the entry point usesfirst line of .venv/bin/inventory-reportthe venv's own python

Fix / how to use it: One environment per project, created next to it as .venv/ and never committed (the snippet .gitignore lists it). Never sudo pip install; never install project dependencies into the OS interpreter. Recreate instead of repair: rm -rf .venv && uv sync (expected; the equivalent on plain pip is python3 -m venv .venv && .venv/bin/python -m pip install -e ".[test]", which ran: 18 passed).

venv, virtualenv and uv venv Important ​

In plain words: Three programs create the same kind of folder. python -m venv is built into Python, virtualenv is the third-party tool of which, per its docs, "Since Python 3.3, a subset of it has been integrated into the standard library under the venv module", uv venv is uv's much faster implementation.

Common misunderstanding: "uv venv environments need pip inside." They do not: the real run of uv venv created bin/, lib/, pyvenv.cfg and a CACHEDIR.TAG, with no pip in site-packages. uv installs into it from outside (uv pip install, uv sync); if a tool insists on pip, uv venv --seed ("Install seed packages (one or more of: pip, setuptools, and wheel) into the virtual environment", per the CLI reference; expected, not run) adds it.

Definition:

ToolShips withInstalls pipInterpreter selectionTypical command
venvCPython 3.3+Yes by default since 3.4 (--without-pip opts out; 21.2.4 here, then upgraded to 26.0.1)The python you runpython3 -m venv .venv
virtualenvpip packageSeeds packages (its docs have a "seeders" plugin point)its own interpreter discovery (not exercised here)virtualenv .venv
uv venvuvNo (opt in with --seed)--python 3.12, .python-version, can downloaduv venv
uv syncuvNorequires-python + .python-versioncreates .venv implicitly
     python3 -m venv plain                       uv venv venv-demo
1    creates bin/ include/ lib/ pyvenv.cfg       creates bin/ lib/ pyvenv.cfg CACHEDIR.TAG
2    seeds pip 21.2.4 + setuptools 58.0.4        seeds nothing (site-packages: _virtualenv.pth only)
3    python -> python3 symlink                   python, python3, python3.9 under bin/
4    activate, activate.csh, activate.fish,      activate, activate.bat, activate.csh, activate.fish,
     Activate.ps1                                activate.nu, activate.ps1, activate.xsh

Real scenario: A pipeline step does python -m venv .venv && .venv/bin/pip install -r requirements.txt and needs 40 seconds of wall time every run; the same step with uv sync --locked uses the global uv cache. A Docker build needs only python -m venv /opt/venv (no extra tool) when uv is not wanted in the image.

Fix / how to use it: On a project with uv, do not create the environment by hand: uv sync creates .venv from requires-python. Use UV_PROJECT_ENVIRONMENT to put it elsewhere; the build for this page did exactly that to keep the repository clean (UV_PROJECT_ENVIRONMENT=<scratch>/uvenv).

pyproject.toml: [build-system], [project] and [tool.*] Must-know ​

Anatomy of pyproject.toml[build-system] (PEP 517 / 518)requires = ["hatchling"]build-backend = "hatchling.build"[project] (PEP 621)name, version, requires-python, readmedependencies = [ "python-dotenv>=1.0", ... ][project.optional-dependencies] extras: ship[project.scripts] console entry points[dependency-groups] (PEP 735)lint, types, dev: local only, never published[tool.*] tables owned by tools[tool.uv] default-groups, sources[tool.ruff] [tool.ruff.lint] [tool.ruff.format][tool.pytest.ini_options] [tool.mypy]Who reads whatpip, build, uv: build-system + projectuv sync: + dependency-groups + [tool.uv]pip install ".[test]": extras onlyuv lock: everything, writes uv.lockruff / pytest / mypy: only their tool tablePoetry 1.x used [tool.poetry] instead

In plain words: One TOML file at the repository root says how the project is built, what it is called, what it needs, and how each tool should behave. It replaces setup.py, setup.cfg, requirements.txt (for declaration), .flake8, pytest.ini and several more.

Common misunderstanding: "pyproject.toml is only for packages I publish." Tools read it for applications too: uv reads [project] and [dependency-groups], Ruff reads [tool.ruff], pytest reads [tool.pytest.ini_options]. An application that is never built still benefits from [project] for its dependency list.

Definition: Three standardised parts. [build-system] (PEP 518, with PEP 517 backends): requires lists what is needed to build, build-backend names the entry point, e.g. hatchling.build, setuptools.build_meta or uv_build. [project] (PEP 621): name, version, description, readme, requires-python, dependencies, [project.optional-dependencies], [project.scripts] and more; dynamic lists fields a build backend computes. [tool.<name>]: free-form tables owned by tools. A fourth table, [dependency-groups] (PEP 735), is covered in the next block.

TableStandardPurposeExample from the snippet
[build-system]PEP 518 / 517How to build the projectrequires = ["hatchling>=1.27"]
[project]PEP 621Metadata and runtime dependenciesrequires-python = ">=3.9"
[project.optional-dependencies]PEP 621Extras (published)api = ["fastapi>=0.115,<1"]
[project.scripts]PEP 621Console entry pointsinventory-report = "inventory.cli:main"
[dependency-groups]PEP 735Local groups (never published)lint = ["ruff>=0.8,<1"]
[tool.hatch.build.targets.wheel]HatchWhere the package livespackages = ["src/inventory"]
[tool.uv]uvuv-only settingsdefault-groups = ["dev"]
[tool.ruff]RuffLinter and formatterline-length = 88
[tool.pytest.ini_options]pytestTest discovery and optionstestpaths = ["tests"]
[tool.mypy]mypyType checker settingsstrict = true

Backends compared. hatchling (the Hatch project's backend) and setuptools both read [project]; uv's uv_build is the default that uv init wrote in the real run (build-backend = "uv_build", requires = ["uv_build>=0.13.10,<0.14.0"]). For an application nobody installs from PyPI the choice rarely matters; for a library choose one and keep it.

     python -m build / pip install . / uv sync  (build-system in action)
1    read pyproject.toml -> [build-system].requires = ["hatchling>=1.27"]
2    create an isolated build environment, install hatchling into it
3    call the backend (PEP 517): build_wheel / build_editable
4    wheel: inventory_tool-0.1.0-py3-none-any.whl  (METADATA carries Requires-Dist from [project])
5    installer unpacks the wheel into site-packages (editable: writes a .pth pointing at src/)

Real scenario: A teammate runs pip install -e . on a machine with no hatchling: pip downloads it into the isolated build environment on its own (the real run installed the project with pip 26.0.1 and printed "Successfully built inventory-tool"). A monorepo mixes setuptools libraries and a hatchling service: each directory has its own [build-system].

Fix / how to use it: Keep [project] complete (name, version, requires-python, dependencies) even for apps; put every tool's settings in its [tool.*] table so the root stays one file; resist dynamic = ["version"] until you have a release process that needs it.

Dependencies, extras and dependency groups (PEP 621, PEP 735) Must-know ​

In plain words: dependencies are what the program needs to run. Extras are optional features a user of your package can ask for (pip install "inventory-tool[api]"). Dependency groups are lists for developers (tests, linters) that are never part of the published package.

Common misunderstanding: "Dev dependencies are just extras with another name." PEP 735 draws the line: it "specifies a mechanism for storing package requirements in pyproject.toml files such that they are not included in any built distribution of the project." Extras are metadata that ends up in the wheel and that other people can request; groups are not.

Definition:

MechanismDefined inShips in the wheelInstalled byUse for
dependenciesPEP 621Yes (Requires-Dist)alwayswhat the code imports
[project.optional-dependencies] (extras)PEP 621Yes, with Provides-Extrapip install ".[api]", uv sync --extra apioptional features: api, postgres
[dependency-groups]PEP 735Nouv sync --group lint, pip install --group lint (pip's reference: "Install a named dependency-group from a "pyproject.toml" or "pylock.toml" file")dev, test, lint, docs
requirements.txtpip formatn/apip install -rexported lock, legacy
[tool.poetry.dependencies]Poetry before 2.0tool-specificpoetry installolder Poetry projects (Poetry 2 also reads [project])

A group may include another: in the snippet, dev = [{ include-group = "lint" }, { include-group = "types" }, "pytest>=8,<9", "packaging>=24"]. The specification calls an include "a table with exactly one key, "include-group"". [tool.uv] default-groups = ["dev"] makes uv sync install the dev group without a flag, (default-groups is a documented uv setting; its docs example uses ["docs"]).

     What each install command puts in .venv (real: uv sync, uv tree, pip freeze)
1    pip install -e .                 python-dotenv, tomli (python < 3.11)
2    pip install -e ".[test]"         + pytest, packaging (+ pytest's dependencies)       -> 18 passed
3    uv sync                          runtime + default group dev: ruff, mypy, pytest, packaging  (15 packages here)
4    uv sync --no-dev                 runtime only
5    uv sync --extra api              + fastapi (and starlette, pydantic ...)
6    uv sync --no-default-groups --group lint    runtime + ruff only  (real: "+ ruff==0.17.6")

Real scenario: The Docker image must not contain pytest, ruff or mypy: uv sync --no-dev. The CI lint job only needs ruff: uv sync --no-default-groups --group lint installs the runtime plus ruff. A library offers inventory-tool[api] to users who want the FastAPI integration, but a plain install does not drag FastAPI in.

Fix / how to use it:

GoalCommandEdits
Add a runtime dependencyuv add httpxdependencies (real: wrote "httpx>=0.28.1" first in the list)
Add to the dev groupuv add --dev pytest-cov[dependency-groups] dev
Add to a named groupuv add --group lint ruff[dependency-groups] lint
Add to an extrauv add --optional api uvicornapi = [...] (real: "uvicorn>=0.39.0")
Removeuv remove httpxpyproject, lock, .venv (real: 16 packages uninstalled, dependencies of other packages stay)

Version specifiers (PEP 440) and environment markers (PEP 508) Must-know ​

In plain words: A dependency line says a name, the versions you accept, and optionally "only on this kind of machine". httpx>=0.28,<1 means "0.28 or newer but not 1.0"; tomli>=2.0; python_version < '3.11' means "only install on Python older than 3.11".

Common misunderstanding: "~= is npm's tilde." PEP 440's compatible release is its own thing. The snippet's test spells it out: ~=1.4.2 means >=1.4.2, ==1.4.* (so 1.4.9 matches and 1.5.0 does not), while ~=1.4 means >=1.4, ==1.* (so 1.9.0 matches). Poetry's own caret (^1.2.3) and tilde (~1.2.3) operators are different again: its docs say "Caret requirements allow SemVer compatible updates to a specified version" and call ~1.2.3 a "tilde requirement".

Definition:

SpecifierMeaningExampleMatches
==1.4.2exactpytest==8.4.2only 8.4.2
==1.4.*prefix match==1.4.*1.4.0, 1.4.9
>=1.0,<2range, comma = ANDpython-dotenv>=1.0,<21.0 up to 1.x
~=1.4.2compatible release>=1.4.2, ==1.4.*1.4.9, not 1.5
!=1.5.0exclusionrequests>=2,!=2.30.0skips one release
===arbitrary string equalityrareavoid
; python_version < '3.11'PEP 508 environment markertomli>=2.0; python_version < '3.11'tomli on 3.9/3.10 only
[api,test]extras of the dependencyinventory-tool[api,test]>=0.1parsed in test_extras_are_part_of_the_requirement_string

Version order (PEP 440), asserted in the tests: 1.0.dev1 < 1.0a1 < 1.0rc1 < 1.0 < 1.0.post1, and 1.0 == 1.0.0. PEP 440: "Pre-releases of any kind, including developmental releases, are implicitly excluded from all version specifiers, unless they are already present on the system, explicitly requested by the user, or if the only available version that satisfies the version specifier is a pre-release." Real finding with packaging 26.3: "2.0a1" in SpecifierSet(">=1.0") returned True there (the containment operator no longer applies the installer's rule), while SpecifierSet(">=1.0").filter(["1.5", "2.0a1"]) returned ['1.5']; the test asserts filter(), which is the behaviour pip and uv follow ("filter" is what resolvers use).

Marker variableMeaningExample
python_version3.9-style major.minorpython_version < '3.11'
python_full_version3.9.6uv writes python_full_version < '3.10' into uv.lock
sys_platformlinux, darwin, win32pywin32; sys_platform == 'win32'
platform_machinearm64, x86_64wheels per architecture
os_nameposix, ntos_name == 'nt'
extrawhich extra is being installedextra == 'test' (in uv.lock metadata)

Pin vs range. A library should declare ranges (so users can combine it with other libraries); an application should have an exact lock in addition to the ranges in pyproject.toml. Pinning exact versions inside dependencies of a library causes conflicts for its users; ranges in an application without a lock cause "works on my machine".

StyleWritten asGood forRisk
Open lower boundhttpx>=0.28librariesA breaking 1.0 lands unexpectedly
Bounded rangehttpx>=0.28,<1libraries and apps with a lockA bound that is too tight blocks upgrades
Compatible releasehttpx~=0.28.1tools that follow patch releasesMeaning differs from npm, Composer, Poetry
Exact pinhttpx==0.28.1the lockfile, or examples (the FastAPI pilot pins)Impossible to combine with others
Marker-gatedtomli>=2.0; python_version < '3.11'backportsMarker typos silently never match

Caret vs tilde across ecosystems. Composer (its versions article): "~1.2 is equivalent to >=1.2 <2.0.0, while ~1.2.3 is equivalent to >=1.2.3 <1.3.0", and "^1.2.3 is equivalent to >=1.2.3 <2.0.0"; Poetry's caret follows SemVer (an update is allowed if it does not change the left-most non-zero digit); PEP 440 has no caret and only ~=. Tools that read [project] use PEP 440 specifiers; Poetry before 2.0 declared dependencies in [tool.poetry.dependencies] ("Prior Poetry 2.0, dependencies had to be declared in the tool.poetry.dependencies section", per its docs) with its own operators.

Real scenario: python-dotenv>=1.0,<2 resolved to 1.2.1 on Python 3.9 and 1.2.4 on 3.10+ in the real lock, because newer releases dropped 3.9; this is the intended effect of marker-aware resolution, not a bug.

Fix / how to use it: Write ranges in pyproject.toml, let the lock pin; test your specifiers with the packaging library (Requirement, SpecifierSet, Marker, Version) rather than reading them by eye; the snippet's tests/test_environment.py is the template.

uv: from pyproject.toml to uv.lock to .venvpyproject.tomldependencies, extras,dependency-groups,requires-pythonranges: what you wantuv lock (resolver)PyPI metadata + cacheuniversal: all markersforks on python_versionhighest compatibleuv.lockexact versionsmarkers per packagecommit to gitpylock.toml: PEP 751.venvuv syncinstalls the lockdrops extrasCommands that touch the lockuv add / uv remove: edit pyproject, re-lock, syncuv lock: re-resolve (--upgrade-package to bump)uv sync: lock if stale, then installuv run: lock + sync (inexact), then runuv export: write requirements.txt with hashesGuards for CI and Docker--locked: fail if uv.lock is out of date--frozen: use uv.lock without checking--no-dev, --no-group, --extra, --group--no-install-project: dependencies only--no-editable: copy the project in

uv projects: uv init, uv add, uv remove, uv lock, uv sync, uv run Must-know ​

In plain words: You tell uv what the project needs (uv add httpx); uv edits pyproject.toml, works out exact versions into uv.lock, and installs them into .venv. uv run pytest runs a command inside that environment, creating or updating it first if needed.

Common misunderstanding: "uv sync is pip install -r." uv sync is "exact" by default: "uv sync performs "exact" syncing by default, which means it will remove any packages that are not selected for installation". "Selected" matters: extras are not synced by default ("uv does not sync extras by default. Use the --extra option to include an extra"), so a package that is in uv.lock but belongs to an unselected extra or to a group excluded with --no-dev is removed too. uv run, in contrast, uv run "uses "inexact" syncing by default" and leaves extraneous packages alone. The real run proves it: after uv sync --locked --no-dev uv printed Uninstalled 14 packages (ruff, mypy, pytest and friends).

Definition:

CommandWhat it doesTouches
uv init NAMENew project. Real: .python-version (3.9), README.md, pyproject.toml, src/shop_api/; [project.scripts] and build-backend = "uv_build"files
uv init --lib NAMELibrary template; real: src/shoplib/__init__.py plus py.typedfiles
uv add PKGAdd to dependencies, resolve, lock, syncpyproject, lock, .venv
uv add --dev / --group G / --optional EAdd to a group or an extrasame
uv remove PKGThe reversesame
uv lockResolve only; --check verifies; --upgrade / --upgrade-package P bumplock
uv syncLock if needed, then make .venv match; flags --extra, --group, --no-dev, --no-default-groups, --no-install-project, --no-editable, --frozen, --locked, --inexact.venv
uv run CMDLock + sync (inexact), then run CMD in the environment; --with PKG adds a one-off dependency; --no-sync, --locked, --frozenmaybe all
uv treePrint the resolved dependency treenone
uv exportWrite requirements.txt, pylock.toml (PEP 751) or CycloneDX outputstdout
     uv add httpx   (real transcript, uv-add-remove.txt, run in a scratch copy)
1    read pyproject.toml; resolve all packages for all Python versions  -> "Resolved 49 packages in 2.08s"
2    insert "httpx>=0.28.1" at the top of [project] dependencies (sorted)
3    write uv.lock
4    create .venv if absent ("Creating virtual environment at: ...")
5    build the project (hatchling) and install: + anyio, certifi, h11, httpcore, httpx==0.28.1, idna ...
     uv remove httpx
6    resolve again -> "Resolved 54 packages"; uninstall httpx and what only it needed (16 packages)

Real scenario: The first hour on a new laptop: git clone, uv sync (creates .venv, installs 15 packages for the snippet), uv run pytest (18 passed in 0.08 s). A teammate edits pyproject.toml by hand to add a library and forgets to lock: uv run --locked pytest fails in CI with an out-of-date lock error instead of silently re-resolving (the flag's documented purpose: "If the lockfile is not up-to-date, uv will raise an error instead of updating the lockfile").

FlagMeaningUse in
--lockedError if uv.lock does not match pyproject.toml (same as uv lock --check)CI, Docker final sync
--frozenUse uv.lock as is, no staleness checkDocker layer that has no pyproject.toml yet, offline use
--no-syncDo not touch the environmentscripted runs
--no-dev / --no-default-groupsSkip the default dev groupproduction images
--extra E / --group GInclude an extra or a groupfeature builds, lint job
--no-install-projectInstall dependencies onlycacheable Docker layer
--no-editableCopy the project into site-packagesmulti-stage images

Fix / how to use it: Commit pyproject.toml, uv.lock and .python-version; ignore .venv. Add dependencies with uv add, never by editing .venv. In CI always uv sync --locked. Re-resolve deliberately: "uv will prefer the previously locked versions of packages when running uv sync and uv lock. Package versions will only change if the project's dependency constraints exclude the previous, locked version."

uv python: managing interpreters Important ​

In plain words: uv can find the interpreters already on your machine and download others, so "install Python 3.13" becomes one command that behaves the same on macOS, Linux and Windows.

Common misunderstanding: "uv replaces my system Python." Managed builds live in uv's own directory; the system interpreter is untouched, and uv uses an installed interpreter that satisfies the request before downloading (real run: uv python find printed /Library/Developer/CommandLineTools/usr/bin/python3 and uv python list --only-installed showed cpython-3.9.6-macos-aarch64-none /usr/bin/python3; with UV_PYTHON_DOWNLOADS=never set, as here, nothing was downloaded).

Definition:

CommandDoes
uv python listLists available and installed interpreters (--only-installed filters)
uv python install 3.12Downloads a managed CPython (uv python install 3.12.3, '>=3.8,<3.10' also work per the docs)
uv python findPrints the interpreter uv would use
uv python pin 3.12Writes .python-version in the current directory (--global for the user config)
uv venv --python 3.12 / uv run --python 3.12 ...Use a specific version for one invocation
     Discovery of Python versions (uv docs, abridged)
1    managed installations in UV_PYTHON_INSTALL_DIR are checked first (newest first)
2    then python, python3 or python3.x on PATH (the first compatible one, not the newest)
3    on Windows also the registry and Microsoft Store interpreters
4    each candidate is queried; one that fails the version request is skipped
5    nothing found: "uv will check for a compatible managed Python version download"
6    a project's .python-version (searched in the working directory and parents, not beyond the
     project or workspace boundary) and requires-python form the request

Real scenario: .python-version contains 3.9 in the real uv init run, because 3.9 was the interpreter found; on a developer machine with 3.13 it would contain 3.13. CI uses setup-uv with a matrix python-version, which sets UV_PYTHON and "will override any python version specifications in pyproject.toml, .python-version, and …", per the setup-uv README.

Fix / how to use it: Commit .python-version with the version you deploy (3.12 or 3.13 for new work), keep requires-python as the lowest version you test, and prefer UV_PYTHON_DOWNLOADS=never in Docker images where the base image already provides the interpreter (as the snippet's Dockerfile does). Expected, not run: uv python install 3.13, uv python pin.

uvx and uv tool: running tools without a project Important ​

In plain words: Some tools (ruff, black, httpie, cookiecutter) are programs, not libraries of your project. uvx ruff check . downloads ruff into a throwaway environment and runs it; uv tool install ruff keeps it on your PATH.

Common misunderstanding: "uvx pollutes my project environment." The docs say tools run in a "virtual environment isolated from the current project", and uvx is an alias: "a uvx alias is provided for uv tool run". Nothing is added to .venv or pyproject.toml. The real run: uvx ruff --version printed Installed 1 package in 3ms then ruff 0.17.6; uv tool install ruff put the executable in the tool bin directory and warned it was not on PATH.

Definition:

CommandPersistenceEnvironmentTypical use
uvx TOOL / uv tool run TOOLnone (cached)temporaryone-off: uvx ruff format --check .
uv tool install TOOLinstalledone per tooldaily tools; uv tool list, uv tool upgrade
uv run --with PKG CMDnoneproject env + extra packagetry httpx==0.26.0 against the project
pipx run / pipx installequivalent ideaper tooluv's docs recommend pipx install uv when installing from PyPI

Real scenario: A contributor without the dev group runs uvx ruff check . before pushing; a project pins ruff in the lint group so that CI and local formatting agree (the snippet), and the Makefile runs uv run ruff, not uvx, for exactly that reason.

Fix / how to use it: Use uv run for tools whose version must match the lock (ruff, mypy, pytest); use uvx for tools that do not care about your code's environment (cookiecutter, httpie). Install uv itself once: curl -LsSf https://astral.sh/uv/install.sh | sh, brew install uv, pipx install uv, pip install uv and on Windows (from the same uv installation page, expected, not run) powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" or winget install --id=astral-sh.uv -e (all expected, not run except pip install --user uv, which produced uv 0.13.10).

Inline script metadata (PEP 723) Important ​

In plain words: A single .py file can carry its own dependency list in a special comment block at the top. uv run script.py reads it, builds a cached environment and runs the file; nothing else is needed.

Common misunderstanding: "That is just a requirements.txt in a comment." The block is a standard (PEP 723) TOML document: # /// script, lines starting # , then # ///. The spec: "Block MUST end with the line # ///", and "Every line between these two lines (# /// TYPE and # ///) MUST be a comment starting with #". It can carry requires-python and dependencies, and any tool may read it, not only uv.

Definition and real run: The snippet's scripts/where_am_i.py declares python-dotenv>=1.0. uv run scripts/where_am_i.py printed (abridged):

1    executable : <scratch>/uvcache/environments-v2/where-am-i-4baac793980093e6/bin/python
2    prefix     : <scratch>/uvcache/environments-v2/where-am-i-4baac793980093e6
3    base_prefix: /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9
4    in a venv  : True
5    dotenv from: <scratch>/uvcache/environments-v2/where-am-i-4baac793980093e6/lib/python3.9/site-packages/dotenv/__init__.py

The script ran in a cached ephemeral environment named after the script, not in the project's .venv. uv lock --script wrote a lock next to it (Resolved 2 packages in 3ms), and a shebang #!/usr/bin/env -S uv run --script makes the file directly executable (documented, expected, not run).

Real scenario: A migration helper, a one-off data fix or a benchmark that must run on a colleague's laptop without a project: email the file, say "install uv, run it". It replaces the "pip install these three things first" paragraph.

Fix / how to use it: Use inline metadata for single-file tools; once a script grows imports from your package, make it part of the project and run it with uv run python -m package.module.

uv pip: the pip-compatible interface Important ​

In plain words: uv pip install, uv pip compile, uv pip freeze, uv pip list and uv venv behave like the pip, pip-tools and virtualenv commands, only faster. They exist so existing requirements.txt workflows can move without rewriting everything.

Common misunderstanding: "It is a perfect drop-in." The compatibility page warns: "the more … pip workflows, the more likely you are to encounter differences in behavior" (the page is titled "Compatibility with pip and pip-tools"). One real difference is environment selection: uv pip list run outside a project used the system interpreter (Using Python 3.9.6 environment at: /Library/Developer/CommandLineTools/...) and listed nothing, because UV_PROJECT_ENVIRONMENT applies to project commands, not to the pip interface; set VIRTUAL_ENV or pass --python for the pip interface.

Definition:

pip / pip-tools / virtualenvuvNote
python -m venv .venvuv venvno pip inside by default
pip install -r requirements.txtuv pip install -r requirements.txtinto the active venv
pip freezeuv pip freezesame idea
pip-compile requirements.inuv pip compile requirements.inby default "produces a resolution that is platform-specific, like pip-tools"
pip-sync requirements.txtuv pip sync requirements.txtexact sync
(no equivalent)uv lock / uv syncuniversal lock; the project interface

Real scenario: A company has 40 repositories with requirements.in and pip-compile. Switch the CI install step to uv pip sync first (same files, faster), then migrate repository by repository to pyproject.toml + uv.lock.

Fix / how to use it: Use the project interface (uv add, uv sync, uv run) for new work and the pip interface only for compatibility; do not mix uv pip install into a project environment managed by uv sync (an exact uv sync will remove what it did not lock).

Workspaces Good to know ​

In plain words: A workspace is several Python packages in one repository that share one lockfile, like a Go workspace or a Composer path-repository monorepo.

Common misunderstanding: "Every package in a workspace has its own lock." uv's docs: "In a workspace, each package defines its own pyproject.toml, but the workspace shares a single lockfile, ensuring that the workspace operates with a consistent set of dependencies."

Definition: The root pyproject.toml has [tool.uv.workspace] with members (required) and exclude (optional); a member depends on another with { workspace = true } under [tool.uv.sources]. uv run and uv sync target the workspace root by default; --package NAME selects a member. In a Docker build the lock cannot be checked before all member pyproject.toml files are copied, so the docs use --no-install-workspace with --frozen for the dependency layer and --locked afterwards.

     monorepo (illustrative layout; not run)
1    repo/pyproject.toml            [tool.uv.workspace] members = ["packages/*"]
2    repo/uv.lock                   one lock for all members
3    repo/packages/api/pyproject.toml     depends on "inventory-core"  ([tool.uv.sources] workspace = true)
4    repo/packages/inventory-core/pyproject.toml
5    uv sync --package api          installs api and its workspace dependency

Real scenario: A FastAPI app plus two internal libraries versioned together; or a service and a worker sharing a models package. For a single deployable service, a plain project is simpler.

The uv cache and why it is fast Important ​

In plain words: uv keeps downloaded and built packages in one global cache and links them into each environment instead of copying or re-downloading, so a second environment with the same packages is nearly free.

Common misunderstanding: "The cache lives in .venv." It is global (uv cache dir prints it; this build redirected it with UV_CACHE_DIR=<scratch>/uvcache). Throwing away .venv does not throw away the downloads.

Definition: The cache docs: "uv uses aggressive caching to avoid re-downloading (and re-building) dependencies that have already been accessed in prior runs", with different keys per source: registry packages "respect HTTP caching headers"; Git dependencies are keyed by "the fully-resolved Git commit hash"; local dependencies by "the last-modified time". The install method is link-mode: "Defaults to clone (also known as Copy-on-Write) on macOS and Linux, and hardlink on Windows".

Observation (real run)Value
First uv lock with a cold cache, 44 packagesResolved 44 packages in 5.67s
Second uv lock on the same projectResolved 44 packages in 2ms
Create venv + install 15 packages (cache warm for most)Prepared 15 packages in 2.51s, Installed 15 packages in 16ms
Add httpx (uncached metadata)Resolved 49 packages in 2.08s
Recreate with everything cachedinstalls in single-digit milliseconds

The times depend on the network and the machine; the shape (resolve is the slow part, install from cache is milliseconds) is the point. Speed comes from Rust, parallel downloads, the cache and the link mode; the page does not quote Astral's benchmark numbers because they were not verified here.

Fix / how to use it: In CI cache the uv cache directory keyed by uv.lock (setup-uv does this with enable-cache); in Docker use a BuildKit cache mount at /root/.cache/uv and UV_LINK_MODE=copy, because "Changing the UV_LINK_MODE silences warnings about not being able to link files since the cache and sync target are on separate file systems" (Docker guide); "The uv cache prune --ci command is used to reduce the size of the cache and is optimized for CI" (GitHub guide; not run).

Lockfiles: uv.lock, requirements.txt, hashes and platform markers Must-know ​

In plain words: pyproject.toml says "httpx 0.28 or newer"; the lockfile says "httpx 0.28.1, with these file hashes, on these Python versions". Commit both. Deploy from the lock.

Common misunderstanding: "A lockfile is for one OS." uv's is "a universal or cross-platform lockfile that captures the packages that would be installed across all possible Python markers such as operating system, architecture, and Python version." The real lock proves it: one file, resolution-markers for four Python ranges, and packages that appear more than once with marker = "python_full_version < '3.10'" conditions.

Definition: A lock records the full resolved graph with exact versions, sources, per-file hashes and the markers under which each entry applies. uv: "The lockfile contains the exact resolved versions that are installed in the project environment. This file should be checked into version control, allowing for consistent and reproducible installations across machines." It is TOML but "managed by uv and should not be edited manually."

     Real excerpt of uv.lock (runs/uv-lock-excerpt.txt, generated by uv 0.13.10)
1    version = 1 ; revision = 5 ; requires-python = ">=3.9"
2    resolution-markers = ["python_full_version >= '3.15'",
3        "python_full_version >= '3.11' and python_full_version < '3.15'",
4        "python_full_version == '3.10.*'", "python_full_version < '3.10'"]
5    [[package]] name = "inventory-tool" version = "0.1.0" source = { editable = "." }
6    dependencies = [ { name = "python-dotenv", version = "1.2.1", ..., marker = "python_full_version < '3.10'" },
7                     { name = "python-dotenv", version = "1.2.4", ..., marker = "python_full_version >= '3.10'" },
8                     { name = "tomli", marker = "python_full_version < '3.11'" } ]
9    [package.optional-dependencies] api = [ fastapi 0.128.8 (<3.10), 0.162.5 (==3.10.*), 0.165.0 (>=3.11) ]
10   [package.metadata] requires-dist = [ ... specifier = ">=1.0,<2" ... ]   <- the pyproject ranges, copied

uv export turns that into the formats other tools read (real, export-nodev-*.txt):

$ uv export --no-dev --no-hashes --no-emit-project
python-dotenv==1.2.1 ; python_full_version < '3.10'
    # via inventory-tool
python-dotenv==1.2.4 ; python_full_version >= '3.10'
    # via inventory-tool
tomli==2.5.0 ; python_full_version < '3.11'
    # via inventory-tool

Without --no-hashes every line carries --hash=sha256:... continuations (two hashes for python-dotenv 1.2.1: 42667e89... and b81ee956...). pip's hash-checking mode (--require-hashes, from its secure-installs page) then refuses any file that does not match, which is the supply-chain half of "reproducible installs".

FormatWritten byRead byCross-platformHashesNotes
uv.lockuvuv onlyyes (universal)yes"specific to uv"
requirements.txt from uv exportuvpip, uv pip, Docker legacyyes, through markers per lineoptionalfor deploy tools that only know pip
requirements.txt from pip-compilepip-toolspipno (platform-specific)optional (--generate-hashes)"pip-tools = pip-compile + pip-sync"
poetry.lockPoetryPoetrynot verified herenot verified heretool-specific (Poetry's saved introduction only establishes repeatable installs)
pdm.lockPDMPDMnot verified herenot verified heretool-specific (its docs list "Lock Files")
pylock.toml (PEP 751)several toolsseveralby designyesthe standard; uv export supports it
composer.lockComposerComposern/adist referencescompare below
go.sumGoGoyeschecksumscompare below

Real scenario: A security patch for one library: uv lock --upgrade-package httpx, uv sync, run tests, commit uv.lock. A reviewer sees exactly one version bump in the lock diff. A deploy server cannot run uv: uv export --no-dev --no-emit-project --output-file requirements.txt in CI, then pip install --require-hashes -r requirements.txt on the server (expected, not run).

Fix / how to use it: Always commit the lock; treat a lock diff as part of code review; set CI to uv sync --locked; do not hand-edit; regenerate on a different machine only through uv lock. The uv docs also note that a lock is not invalidated by new releases: "uv will not consider lockfiles outdated when new versions of packages are released".

pip, pip-tools, Poetry, PDM, Rye, Hatch and uv: choosing Important ​

In plain words: All of them install packages; they differ in whether they also lock, create environments, build packages and manage interpreters.

Common misunderstanding: "Pick the newest tool and migrate everything." The pragmatic rule: new projects use uv; existing Poetry or PDM projects keep working and can move when there is a reason; pip and pip-tools remain the compatibility layer. Rye needs no choice: its docs say "Rye is no longer developed … We encourage all users to use uv".

Definition (what each is, from its own docs where fetched):

ToolCreates envsLocksManages Python versionsReads [project] (PEP 621)Notes
pipno (use venv)pip lock exists (it appears in pip's command list; the saved pages do not describe its output, though pip can install from pylock.toml); it is a command, not a project workflow that re-locks on add and keeps .venv in sync the way uv.lock doesnoyes (pip install ., --group)the installer every other tool builds on
pip-toolsnopip-compile writes pinned requirements.txtnoyes"pip-compile + pip-sync"
virtualenv / venvyesnonon/aenvironment only
pyenvnonoyes (shims; compiles from source)n/aversion management only
Poetryyespoetry.lockno (not verified here)from Poetry 2.0; before that [tool.poetry]"Python dependency management and packaging made easy"
PDMyespdm.lock (its docs list "Lock Files")yes ("Install Pythons using indygreg's python-build-standalone")yes ("PEP 621 project metadata")also "A PEP 517 build backend"; has a PEP 582 mode (not covered here)
Hatchyes (its docs list Environment, and "Dependency locker" among its plugin kinds)via plugin, not the core workflownot verified hereyesalso the home of the hatchling backend
Ryeyesyesyesyesdiscontinued February 2025; successor is uv
uvyesuv.lockyesyes"A single tool to replace pip, pip-tools, pipx, poetry, pyenv, twine, virtualenv, and more" (uv docs)

Real scenario: A team inherits a requirements.txt with 300 unpinned lines, a Pipfile, and a Dockerfile running pip install -r. The path: uv init, uv add -r requirements.txt (documented form, not run here), uv lock, then uv sync --locked in the Dockerfile. A library author with a setup.py can keep setuptools as the build backend and still use uv to run the tests.

Fix / how to use it: For applications choose uv. For published libraries choose uv or Hatch for development and a [build-system] backend that reads [project] (hatchling, setuptools, uv_build). Keep requirements.txt only as an export.

Ruff: the linter (ruff check) Must-know ​

In plain words: Ruff reads your Python and reports mistakes and style problems with short codes (F401 unused import, E711 comparison to None, B006 mutable default argument); for many of them it can also rewrite the code. It is one program that re-implements what flake8 and its plugins, isort and pyupgrade did.

Common misunderstanding: "Ruff only checks style." Rule families include real bug finders: F (Pyflakes: undefined names, unused imports), B (flake8-bugbear: mutable defaults, except traps), E7/E9 (statement and syntax errors). The real run on the messy file found a bare except (E722) and a mutable default (B006) next to the cosmetic issues.

Definition: Codes are "Flake8-style rule codes: an alphabetic prefix followed by digits (e.g., F401)", selected "by a full rule code (e.g., F401) or any valid prefix (e.g., F)". Ruff "supports over 900 lint rules split across over 50 built-in plugins", and its default set enables rules from "the F, E, B, UP, and RUF categories, as well as many more, omitting any stylistic rules that overlap with the use of a formatter". The snippet makes the choice explicit:

PrefixOriginCatchesIn the snippet
E / Wpycodestylestyle and syntax: E711 == None, E722 bare except, E501 line too longE selected, E501 ignored (the formatter owns line length)
FPyflakesunused imports and variables, undefined namesselected
Iisortimport order and grouping (I001)selected (isort rules)
UPpyupgradeoutdated syntax for the target version (UP035, UP006)selected, depends on target-version = "py39"
Bflake8-bugbearlikely bugs (B006, B017)selected
RUFRuff-specificrules only Ruff hasdefault set; not selected explicitly here
C90mccabecomplexitynot selected
Npep8-namingnamingnot selected
Sflake8-banditsecurity smellsnot selected; a good addition for web code
     $ ruff check lint_demo/messy.py --output-format concise   (real run, Ruff 0.17.6)
1    lint_demo/messy.py:1:1: E401 [*] Multiple imports on one line
2    lint_demo/messy.py:1:1: I001 [*] Import block is un-sorted or un-formatted
3    lint_demo/messy.py:1:8: F401 [*] `sys` imported but unused
4    lint_demo/messy.py:1:13: F401 [*] `os` imported but unused
5    lint_demo/messy.py:2:1: UP035 `typing.List` is deprecated, use `list` instead
6    lint_demo/messy.py:6:44: UP006 Use `list` instead of `List` for type annotation
7    lint_demo/messy.py:6:56: B006 Do not use mutable data structures for argument defaults
8    lint_demo/messy.py:7:16: E711 Comparison to `None` should be `cond is None`
9    lint_demo/messy.py:11:5: E722 Do not use bare `except`
10   Found 9 errors.
11   [*] 4 fixable with `--fix` (3 unsafe fixes available with `--fix --unsafe-fixes`).

Two details worth reading from that output. Optional[str] on line 6 is not flagged: with target-version = "py39" the modern str | None syntax is not allowed at runtime on 3.9, so UP045 stays quiet; typing.List is flagged because list[str] works from 3.9. Real run with --isolated --target-version py310 --select UP: UP045 [*] Use \X | None` for type annotationsappears at 6:16 next toUP035andUP006, and two of the three become fixable. Second: [*]` marks "fixable", and the unsafe ones are described by the docs: "an unsafe fix could lead to a change in runtime behavior, the removal of comments, or both".

CommandDoesReal result on messy.py
ruff check .Lint; exit code 1 if anything is foundAll checks passed! on the project (the demo file is in extend-exclude)
ruff check --fixApply safe fixesFound 9 errors (4 fixed, 5 remaining)
ruff check --fix --unsafe-fixesAlso apply unsafe fixesFound 5 errors (4 fixed, 1 remaining); E722 (bare except) has no fix
ruff check --statisticsCount findings per rule2 F401, 1 E722, 1 UP035, 1 E401, 1 B006, 1 UP006, 1 E711, 1 I001
ruff rule F401Explain a ruleprints "unused-import (F401)", "Derived from the Pyflakes linter"
ruff check --select E,F,I,UP,BOverride the configured set for one runsame set as the config
ruff check --add-noqaAdds a # noqa directive to each line with a violation (the tutorial's way to adopt Ruff on old code)not run

The unsafe fix is a lesson of its own: the result of --fix --unsafe-fixes turned seen: List[str] = [] into seen: list[str] = None and added if seen is None: seen = [], which is the correct repair of B006 but leaves a wrong annotation (list[str] given None); a human must still change the annotation. On Python 3.9 write Optional[list[str]] (as the demo file already imports Optional); list[str] | None is only safe at runtime on 3.10+, or on 3.9 in a module with from __future__ import annotations (annotations are then never evaluated). That is also why UP045 only fires once target-version is py310. That is why unsafe fixes are opt-in.

Real scenario: A review comment "please sort your imports" disappears when I is selected. A junior's def f(items=[]) is caught before it ships a shared-state bug. An old codebase with 3,000 findings adopts Ruff by selecting only F first and widening the set each sprint.

Configuration lives in pyproject.toml, ruff.toml or .ruff.toml, and "Ruff supports hierarchical configuration. For each file, Ruff uses the "closest" config file in the directory hierarchy."

toml
[tool.ruff]
line-length = 88
target-version = "py39"
src = ["src", "tests"]
extend-exclude = ["lint_demo"]

[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
ignore = ["E501"]

[tool.ruff.lint.per-file-ignores]
"tests/**" = ["B011"]

[tool.ruff.format]
quote-style = "double"
SettingMeaning
line-lengthThe formatter's target and the linter's E501 limit (88 is Black's default)
target-versionOldest Python the code must run on; controls UP rules and syntax checks
srcWhere first-party imports live, so I sorts inventory as first-party
extend-excludeSkip paths in addition to the defaults
select / extend-select / ignoreRule sets by prefix or code
per-file-ignoresRules to skip for matching paths, e.g. "tests/**"
[tool.ruff.lint.isort]known-first-party, combine-as-imports, section order
# noqa: F401Suppress one rule on one line

Fix / how to use it: Select explicitly (E, F, I, UP, B is a sound start), ignore E501 if you format with Ruff, pin Ruff in the lint group so CI and laptops agree, and run ruff check --fix then ruff format locally. Add S, C4, SIM or RUF only when you can explain what they buy.

Ruff: the formatter (ruff format) and Black compatibility Must-know ​

In plain words: ruff format rewrites a file into one canonical layout: double quotes, 88 columns, one argument per line when a call does not fit, trailing commas. You stop discussing layout in reviews.

Common misunderstanding: "Switching from Black will reformat my whole repository." The Ruff formatter "is intended to emit near-identical output when run over existing Black-formatted code. When run over extensive Black-formatted projects like Django and Zulip, > 99.9% of lines are formatted identically." It also has "known, intentional differences" documented on a dedicated page; read it before the first run on a Black codebase.

Definition: "The Ruff formatter is an extremely fast Python code formatter designed as a drop-in replacement for Black, available as part of the ruff CLI via ruff format." ruff format --check "will avoid writing any formatted files back, and instead exit with a non-zero status code upon detecting any unformatted files"; --diff prints what would change.

     $ ruff format --diff lint_demo/messy.py       (real, after the lint fixes)
1    --- lint_demo/messy.py
2    +++ lint_demo/messy.py
3    -    return {"path":path,   "data": data,"items":[ str(x) for x in range(3) ]}
4    +    return {"path": path, "data": data, "items": [str(x) for x in range(3)]}
5    1 file would be reformatted

Real scenario: The snippet's first real ruff format --check . reported 1 file would be reformatted: a comment trailing an assertion in the test file was longer than 88 columns, and the diff showed the formatter moving it; the fix was to move the comment above the statement. After that: 11 files already formatted.

QuestionAnswer
Lint and format with one tool?Yes: ruff check and ruff format are separate commands of one binary
Does ruff check --fix replace the formatter?No; I001 fixes import order, not layout
Black or Ruff for new code?Ruff (same style, one tool, fewer dependencies); keep Black on projects that already run it until you have time to diff
Do pragma comments change line width?No: "Pragma comments (# type, # noqa, # pyright, # pylint, etc.) are ignored when computing the width of a line"
Conflicts between E501 and the formatter?Ignore E501 (the snippet does) or keep both at the same line-length

Fix / how to use it: Local: uv run ruff check --fix . && uv run ruff format . (the Makefile and justfile fmt/lint recipes). CI: ruff check . and ruff format --check .; never let CI rewrite files.

Ruff in the workflow: pre-commit, editors and CI Important ​

In plain words: A pre-commit hook runs Ruff on the files you are about to commit, so style failures never reach CI.

Common misunderstanding: "pre-commit replaces CI." Hooks run on a developer's machine and can be skipped with git commit --no-verify; CI is the gate that cannot be skipped.

Definition: pre-commit (pre-commit.com) installs Git hooks from .pre-commit-config.yaml. Ruff's hooks live in the ruff-pre-commit repository; the docs' current example is rev: v0.17.6 with id: ruff-check (add args: [ --fix ]) and id: ruff-format, which is the snippet's .pre-commit-config.yaml.

     pre-commit with Ruff (expected, not run: needs the pre-commit tool and a Git repository)
1    git commit
2    pre-commit stashes unstaged changes, runs ruff-check --fix on staged .py files
3    ruff-format rewrites staged files; hook "fails" if it changed anything
4    you git add the changes and commit again
5    CI repeats: ruff check . ; ruff format --check .    (the unskippable gate)
WhereHowGate?
EditorRuff language server / extension, format on saveno
pre-commit hook.pre-commit-config.yamllocal only
make lint / just lintuv run ruff check . + uv run ruff format --check .local, scriptable
CI jobsame two commandsyes

Fix / how to use it: Pin the hook's rev to the same Ruff version as the lint group (a mismatch makes the hook and CI disagree); run pre-commit autoupdate (documented on pre-commit.com, not run) when you bump Ruff. See Git & Version Control for hooks in general.

Type checking preview: mypy and pyright Good to know ​

In plain words: Type hints do nothing at runtime on their own. A type checker reads them and reports contradictions before you run the code.

Common misunderstanding: "Pydantic or FastAPI already type-check my code." They validate data at runtime; mypy and pyright analyse source statically and are complementary. The language side of hints is in Typing & Pydantic v2.

Definition and real run: mypy 1.19.1 is in the types group; [tool.mypy] strict = true, files = ["src"] produced Success: no issues found in 5 source files on the snippet (real). pyright (Microsoft's checker; its docs site is JavaScript-rendered, so its configuration page and README were saved from GitHub instead) is the alternative; no claim is made here about speed or editor integration. One real wrinkle: the first draft of render() took Sequence[object] and needed # type: ignore[index]; typing the parameter as Sequence[sqlite3.Row] removed the ignore, which is the better fix, and mypy then reported no issues.

mypypyright
Config[tool.mypy] in pyproject.toml (mypy docs: "pyproject.toml (containing a [tool.mypy] section)")[tool.pyright] in pyproject.toml; "A pyrightconfig.json file always takes precedent over pyproject.toml if both are present" (pyright docs)
Run via uvuv run mypyuvx pyright (not run)
In this snippetyes (types group, CI step)no

The previews on this page: the mypy preview is the types group and the CI step; the pyright preview is the uvx pyright alternative. Neither is configured further here, because the typing chapter owns the language side.

Fix / how to use it: Start with strict = false on an existing codebase and tighten per module ([[tool.mypy.overrides]]); a typed src/ and an untyped tests/ is a common middle state.

pytest as a tool, and task runners (uv run, Makefile, justfile) Important ​

In plain words: pytest is just another dependency (in the dev group); you run it with uv run pytest. A Makefile or justfile gives short names to the commands the team repeats.

Common misunderstanding: "I need a task runner like npm scripts." uv run already runs any command in the project environment, and [project.scripts] creates console commands (inventory-report). A Makefile or justfile is convenience for composite steps (lint + test), not a requirement. just describes itself as "a handy way to save and run project-specific commands"; taskipy keeps tasks in [tool.taskipy.tasks] of pyproject.toml. Hatch and PDM have scripts tables, which this page does not cover.

Definition and real run: uv run pytest printed 18 passed in 0.08s (3 files: 4 CLI tests, 5 DB tests, 9 environment tests). The same suite under a plain venv with pip install -e ".[test]" also gave 18 passed in 0.08s, because the test extra mirrors the dev group. The addopts -p no:cacheprovider keeps the working tree free of .pytest_cache.

RunnerSyntaxNeeds installProsCons
uv run CMDno fileuvzero config, always the right environmentno composition
Makefiletarget: + tab-indented recipesmake (present on most Unix)universal, .PHONYtabs, Windows friction
justfilerecipe: + indented bodyjustno tab rule, recipe arguments, default:another binary to install
taskipy[tool.taskipy.tasks] in pyproject.toml ("The complementary task runner for python")pip packagestays in pyproject.tomlPython-only
[project.scripts]name = "pkg.mod:func"nonereal command on PATH of the environmentfor the app's own CLI

The snippet's recipes call uv run inside every target so the runner never needs an activated environment: make lint expands to uv run ruff check . followed by uv run ruff format --check .. (Expected, not run: make and just themselves; the commands they wrap ran.) For how pytest is used against FastAPI see Testing FastAPI.

Fix / how to use it: Keep recipes thin (one command each), keep the real logic in scripts or [project.scripts], and make CI call the same recipes developers call (make lint test), so "passes locally" and "passes in CI" mean the same thing.

Project layout: src/ vs flat Important ​

In plain words: In a flat layout the importable package sits in the repository root next to pyproject.toml; in a src layout it sits one level down in src/. The second forces you to install the project before importing it.

Common misunderstanding: "src is required for packaging." It is not. The Python Packaging User Guide describes both and the trade-off: "The src layout requires installation of the project to be able to run its code, and the flat layout does not." Its argument: "The src layout helps prevent accidental usage of the in-development copy of the code", because "the Python interpreter includes the current working directory as the first item on the import path".

Definition:

Flatsrc
Importable codeinventory/ in the rootsrc/inventory/
Run without installingworks from the root (cwd on sys.path)needs an install (editable is fine)
Tests can import the installed copynot guaranteedyes
uv init defaultnoyes: "uv prefers to define a build system and place source files in a dedicated src/<project_name>/ directory"
Typical forscripts, notebooks, small appslibraries, services with a test suite
     Real: why the editable install matters (plain venv probe, sys.path last entry)
1    pip install -e .                 adds <scratch>/pcopy/src to sys.path through a .pth file in site-packages
2    python -c "import inventory"    works from any directory
3    without the install              ModuleNotFoundError: No module named 'inventory' (src is not on sys.path)

Line 3 is the documented behaviour of the layout; the transcript did not capture that failure, so it is not claimed as a real run. A FastAPI service with routers, services and repositories is organised inside src/<package>/ as described in APIRouter & Project Structure; the pilot FastAPI Fundamentals used a flat app/ for brevity (its pytest sets pythonpath = ["."]).

Fix / how to use it: New services: src layout, [tool.hatch.build.targets.wheel] packages = ["src/<name>"] (or uv_build's default), tests in a sibling tests/, ruff src = ["src", "tests"].

Configuration and .env: python-dotenv and pydantic-settings preview Important ​

In plain words: Secrets and per-machine settings come from environment variables. A .env file is a developer convenience that loads variables from a file; it must never be committed, and real environment variables should win over it.

Common misunderstanding: "load_dotenv() is how production reads config." Production sets real environment variables (Docker -e, Kubernetes, a secret manager); .env is for laptops. The snippet encodes the precedence in load_settings: {**file_values, **os.environ}, so a real variable beats the file (test_real_environment_beats_env_file).

Definition: python-dotenv: load_dotenv() "reads variables from a .env file and sets them in os.environ"; dotenv_values() returns a dict without touching os.environ, which is what the snippet uses so tests stay isolated. pydantic-settings (preview; owned by Typing & Pydantic v2 and APIRouter & Project Structure) gives a typed BaseSettings that reads the environment and an env_file: "If you create a model that inherits from BaseSettings, the model initialiser will attempt to determine the values of any fields not passed as keyword arguments by reading from the environment."

MechanismTypedReads .envPrecedenceWhere to use
os.environ / os.getenvno (strings)noprocess envtiny scripts
python-dotenv load_dotenv()noyesREADME: "Not override existing environment variables (override=False). Pass override=True to override existing variables."scripts, Django-style settings
dotenv_values() + dataclass (snippet)yes (own code)yesexplicit mergetests, small tools
pydantic-settings BaseSettingsyes, validatedyes (env_file)its docs: "environment variables will always take priority over values loaded from a dotenv file"FastAPI services
Laravel .env + env() in config/*.phppartly (reserved values, casts in config)yesLaravel docs: "Any variable in your .env file can be overridden by external environment variables"PHP
     .env hygiene
1    .env.example   committed: names and safe defaults only
2    .env           ignored (.gitignore, .dockerignore): real values
3    CI / prod      set variables in the platform; no .env file in the image
4    tests          set values with monkeypatch.setenv, never read the developer's .env

Real scenario: A developer commits .env with a database password. The remedy is rotation first, history rewrite second; the prevention is the snippet's .gitignore plus a secret scanner in CI (see CI/CD Pipelines).

Fix / how to use it: Typed settings object, one place that reads the environment, .env.example committed, the real .env ignored, and the precedence tested.

Docker images for Python with uv Must-know ​

uv in a multi-stage Dockerfile: what is cached, what is copiedStage 1: builder (python:3.12-slim + uv)COPY --from=ghcr.io/astral-sh/uv:0.13.10 /uv /bin/layer A: uv sync --locked --no-dev (--no-install-project) inputs: uv.lock, pyproject rebuilt only when the lock changeslayer B: COPY src; uv sync --no-editable rebuilt on code change; deps stay cachedENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copyStage 2: runtime (python:3.12-slim)no uv, no pip cache, no source tree, no testsCOPY --from=builder /app/.venv /app/.venvPATH=/app/.venv/bin:$PATHUSER app (not root)CMD inventory-report--no-dev: no ruff, mypy, pytestbytecode already compiled: fast first startBuildKit cache mount: --mount=type=cache,target=/root/.cache/uvthe uv cache survives between builds, and UV_LINK_MODE=copy silences the cross-filesystem hard-link warning

In plain words: A Dockerfile for Python with uv is a multi-stage uv build: in a container the "environment" is the image. Install the locked dependencies in one cached layer, compile bytecode (UV_COMPILE_BYTECODE), copy the code in the next, and ship only the virtual environment to the final image so it holds no uv, no tests and no compilers.

Common misunderstanding: "uv sync in the Dockerfile is enough." Without care it re-installs everything on every code change, ships dev tools and puts the project in editable mode (pointing at a source tree the runtime stage does not have). The three fixes are in the snippet's Dockerfile: --no-install-project for the dependency layer, --no-dev to leave out groups, --no-editable plus copying only /app/.venv.

Definition: uv's Docker guide: "uv sync --no-install-project will install the dependencies of the project but not the project itself. Since the project changes frequently, but its dependencies are generally static, this can be a big time saver." On bytecode: "Compiling Python source files to bytecode is typically desirable for production images as it tends to improve startup time (at the cost of increased installation time and image size)", enabled by --compile-bytecode or ENV UV_COMPILE_BYTECODE=1. On the environment: "It is best practice to add .venv to a .dockerignore file", and ENV PATH="/app/.venv/bin:$PATH" puts the environment's scripts first.

     Build order in the snippet's Dockerfile (expected, not run: no Docker in this environment)
1    FROM python:3.12-slim AS builder ; COPY --from=ghcr.io/astral-sh/uv:0.13.10 /uv /uvx /bin/
2    ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=never
3    RUN --mount=type=cache,... --mount=type=bind,source=uv.lock ... uv sync --locked --no-install-project --no-dev
        layer A: cache key = contents of uv.lock + pyproject.toml
4    COPY pyproject.toml uv.lock README.md ./ ; COPY src ./src
5    RUN ... uv sync --locked --no-dev --no-editable            layer B: reruns when code changes
6    FROM python:3.12-slim ; COPY --from=builder --chown=app:app /app/.venv /app/.venv
7    ENV PATH="/app/.venv/bin:$PATH" ; USER app ; CMD ["inventory-report", "--no-env-file"]
Instruction / flagWhyCost if missing
COPY --from=ghcr.io/astral-sh/uv:0.13.10 /uv /uvx /bin/uv without pip; pinned tag (the docs list ghcr.io/astral-sh/uv:{major}.{minor}.{patch} tags)non-reproducible builds with :latest
--mount=type=bind,source=uv.locklayer A does not copy files, so source edits cannot bust itslow rebuilds
--lockedbuild fails if the lock is staleimage differs from CI
--no-devleave dev group outtest tools in production
--no-install-projectdependency layer onlydeps reinstalled on code change
--no-editableproject copied into site-packagesruntime stage needs the source tree
UV_COMPILE_BYTECODE=1.pyc files exist at startslower first import
UV_LINK_MODE=copyno hardlink warnings with cache mountsnoisy logs
UV_PYTHON_DOWNLOADS=neveruse the base image's Pythonan unexpected interpreter download
USER appnot rootroot in production
.dockerignore: .venv, .env, .gitdo not copy a host environment or secretsbroken platform-specific .venv, leaked secrets

Real scenario: A code-only change: layer A is a cache hit (the lock did not change), layer B copies src/ and installs the project in seconds. A dependency bump: layer A rebuilds, with the BuildKit cache mount supplying already-downloaded wheels. Image size and layer rules are in Images & Dockerfiles; the server process (Uvicorn/Gunicorn) is in FastAPI in Production.

Fix / how to use it: Copy the structure of the snippet's Dockerfile; run docker build yourself (expected, not run here; the commands inside, uv sync --locked --no-dev, were run locally and gave Uninstalled 14 packages, i.e. the dev group was left out).

CI with astral-sh/setup-uv Must-know ​

In plain words: The setup-uv action does the CI caching: the CI job installs uv, restores the uv cache, runs uv sync --locked and then the same lint and test commands you run locally.

Common misunderstanding: "Cache .venv." The docs and the action cache uv's download cache keyed by lock and metadata files, not the environment: setup-uv "Enable the GitHub Actions cache for uv", with cache-dependency-glob controlling the key (default patterns include **/uv.lock, **/pyproject.toml and the requirements files).

Definition: The uv GitHub guide uses astral-sh/setup-uv, pinned by commit with a version comment (@c771a70e… # v9.0.0), and states "It is considered best practice to pin to a specific uv version", via with: version: "0.13.10". The python-version input "sets the environment variable UV_PYTHON" for later steps, overriding .python-version. The snippet's workflow:

     .github/workflows/ci.yml (expected, not run: needs GitHub Actions)
1    checkout (pinned by SHA)
2    setup-uv: version 0.13.10, enable-cache, cache-dependency-glob uv.lock, python-version from the matrix (3.9, 3.12, 3.13)
3    uv sync --locked                    fail if pyproject.toml and uv.lock disagree
4    uv run ruff check .                 lint
5    uv run ruff format --check .        formatting gate
6    uv run mypy                         types
7    uv run pytest                       tests (18 here)
StepCommandFails when
Installastral-sh/setup-uvthe pinned uv version is not available
Syncuv sync --lockedlock is stale or a dependency cannot be resolved for the platform
Lintuv run ruff check .any selected rule fires
Formatuv run ruff format --check .a file is not formatted
Typesuv run mypyany type error under strict
Testuv run pytestany test fails
Cache trim (manual cache variant)uv cache prune --cinever (size only)

Real scenario: A pull request edits pyproject.toml without committing uv.lock: step 3 fails with error: The lockfile at uv.lock needs to be updated, but --locked was provided (real message, captured locally in uv-errors.txt). The matrix includes 3.9 because requires-python = ">=3.9" is a promise that should be tested; with 3.12 and 3.13 it also runs on the versions you deploy. Pipeline mechanics, secrets and OIDC are in CI/CD Pipelines.

Fix / how to use it: Pin the action and the uv version, run exactly the commands in the Makefile, upload nothing from .venv, and never use --frozen in CI (it skips the staleness check that --locked performs).

Mechanics ​

What uv run does, step by step Important ​

In plain words: uv run is "make sure the environment is right, then run my command in it".

Common misunderstanding: "uv run just prefixes .venv/bin." It also locks and syncs first; the docs: "when uv run is used, the project is locked and synced before invoking the requested command."

Definition:

     uv run pytest        (sequence assembled from the docs and the real transcripts)
1    find the project root: nearest pyproject.toml upward
2    select an interpreter (.python-version, requires-python, discovery order)
3    create .venv if missing        "Creating virtual environment at: ..."
4    lock if pyproject.toml changed "Resolved N packages in Xms"   (--locked: error instead; --frozen: skip the check)
5    sync inexactly                 "Installed N packages", "Uninstalled" only with uv sync (exact)
6    put .venv/bin first on PATH, set VIRTUAL_ENV, exec pytest
7    the exit code of pytest is the exit code of uv run

Real scenario: A flaky "works in my shell, fails in cron" job: the cron entry used python3 job.py; uv run --project /srv/app job.py (documented flag, not run) removes the dependence on activation.

WhereWhat uv run changes
PATH.venv/bin first
VIRTUAL_ENVthe project environment
uv.lockupdated if pyproject.toml changed (unless --locked/--frozen)
.venvsynced inexactly (--exact for exact)
working directoryunchanged

Fix / how to use it: In scripts use uv run --locked; in interactive work plain uv run.

Exact messages, errors and what they mean Must-know ​

All rows below are real output (runs/*.txt, uv 0.13.10, Ruff 0.17.6, CPython 3.9.6) unless marked otherwise.

MessageCommandMeaningFix
Using CPython 3.9.6 interpreter at: /Library/Developer/CommandLineTools/...uv lock, uv syncwhich interpreter uv chosepin with .python-version
Resolved 44 packages in 5.67suv lockresolution finished (cold cache)none
Creating virtual environment at: <scratch>/uvenvuv syncfirst sync created .venv (here the UV_PROJECT_ENVIRONMENT location)none
Prepared 15 packages in 2.51s / Installed 15 packages in 16msuv syncdownloaded/built, then linked from the cachenone
Uninstalled 14 packagesuv sync --locked --no-devexact sync removed the dev groupexpected
error: The lockfile at uv.lock needs to be updated, but --check was provided. with cause: Requirements for inventory-tool==0.1.0 differ; added: rich>=13uv lock --checkpyproject.toml changed, lock notuv lock, commit
same text with --locked was provideduv sync --locked, uv run --lockedsame, in CIsame
error: Failed to add dependencies + No solution found when resolving dependencies for split (markers: python_full_version >= '3.15')uv add no-such-package-xyz-123the name does not exist on the indexfix the name
hint: While the active Python version is 3.9, the resolution failed for other Python versions supported by your project.sameuniversal resolution checks every supported Pythonnarrow requires-python or fix the dependency
error: No interpreter found for Python 3.8 in managed installations or search path + hint: A managed Python download is available for Python 3.8, but Python downloads are set to 'never'uv sync --python 3.8exit code 2allow downloads or install 3.8
ModuleNotFoundError: No module named 'inventory'python3 -c "import inventory"system interpreter, project not installed (real, uv-errors.txt)use the environment: uv run python ...
Found 9 errors (4 fixed, 5 remaining).ruff check --fixsafe fixes appliedread the remaining ones
1 file would be reformattedruff format --checknot formatted; exit code non-zerorun ruff format
Success: no issues found in 5 source filesmypycleannone
-e <editable install ...> in pip freezeplain venv + pip install -e .editable project line (git remote redacted in the saved file)normal

Fix / how to use it: Read the cause: line first; uv's errors name the exact requirement that differs.

How pip install -e . and uv sync make the project importable Good to know ​

In plain words: "Editable" means the environment contains a tiny pointer to your src/ directory instead of a copy, so edits are visible immediately.

Common misunderstanding: "Editable installs are for production." They are for development; production uses a non-editable install (--no-editable, a built wheel).

Definition: Hatchling's editable build writes a .pth file (_editable_impl_inventory_tool.pth in the uv environment's site-packages, real) that adds src/ to sys.path; the plain-venv probe showed <scratch>/pcopy/src as the last sys.path entry. Files in .pth that name directories are added by the site machinery at start-up.

     editable vs regular install
1    regular:  site-packages/inventory/*.py   (copy of the code, frozen at install time)
2    editable: site-packages/_editable_impl_inventory_tool.pth -> <project>/src
3    edit src/inventory/db.py -> editable: next run sees it; regular: needs a reinstall

Real scenario: A test passes locally and fails in the image because the image stage had an editable install pointing at a directory it did not copy: the reason the snippet's Dockerfile uses --no-editable.

Fix / how to use it: Development: uv sync (editable by default per the uv docs: "By default, uv installs projects and workspace members in editable mode"). Production: uv sync --no-editable or install a built wheel.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limit
"Works on my machine"Lock + --lockedcommit uv.lock; CI uv sync --lockedSame versions everywhereLock diffs in reviews
Wrong PythonPin the version.python-version, requires-python, CI matrixFails earlyAnother file
Global pollutionEnvironment per projectuv sync creates .venvIsolationDisk (cache hardlinks/clones reduce it)
Dev tools in prodGroups + --no-dev[dependency-groups], Docker --no-devSmall, safer imageMust remember the flag in every command
Slow CI installsCache keyed by locksetup-uv enable-cache, cache-dependency-globSecondsCache invalidation when the lock changes
Style argumentsOne formatterruff format + CI checkNo review noiseA one-time reformat commit
Unused imports, mutable defaultsOne linterruff check with E F I UP BFast feedbackRule choice needs thought
Secrets in Git.env ignored, example committed.gitignore, .dockerignoreNo leaksNeeds scanning as a backstop
Many packages in one repoWorkspace[tool.uv.workspace]One lockCoupled releases
Legacy deploy tooling wants pipExportuv export --no-dev > requirements.txtKeeps old pipelineTwo formats to keep in sync (generate, never edit)

Reproducible installs, concretely ​

Three levels, from weakest to strongest: (1) ranges only: pip install . resolves today's newest compatible versions; (2) exact lock: uv sync --locked installs versions from uv.lock; (3) lock plus hashes: uv export with hashes and pip install --require-hashes -r requirements.txt refuses any file whose SHA-256 differs. The real export showed two hashes for python-dotenv 1.2.1 (a wheel and an sdist). Level 2 is the default for applications; level 3 is for regulated or high-risk deployments.

Keeping the toolchain itself reproducible ​

A lock pins your dependencies, not uv, Ruff or Python. Pin Ruff in the lint group (done: ruff>=0.8,<1 is a range, and the lock holds 0.17.6; the pre-commit rev is pinned to the same), pin uv in CI (version: "0.13.10") and in the Docker COPY --from tag, and pin the base image to a minor version (python:3.12-slim). The ruff entry in the lock is the single source of truth for local and CI; the pre-commit rev is the one number that must be changed by hand (or by pre-commit autoupdate).

Choosing ​

SituationRecommendationExtra techniqueReason
New FastAPI serviceuv project, src layout, hatchling or uv_build.python-version, uv sync --locked in CIOne tool, one lock
Existing Poetry projectKeep Poetry until there is a reason; try uv on a branchConvert [tool.poetry] to [project] firstPoetry 2 reads [project]
Existing requirements.txt workflowuv pip sync first, then migrate to pyproject.tomluv add -r requirements.txtIncremental
One-off scriptPEP 723 block + uv runuv run --with for experimentsNo project needed
Published library[build-system] + ranges, extras for optional featuresmatrix over Python versions, ruff + mypyUsers combine your ranges
Data/ML notebookGroups for heavy extras, interpreter pinnedUV_PYTHONLarge wheels are cached
MonorepoWorkspaceuv sync --packageOne lock
Air-gapped deployuv export with hashes, vendored wheelspip install --no-index --find-links (documented pip option, not run)No network at install
Tool for everyone (formatter)uvx ruff or uv tool install ruffpin in lint group for CIConsistent output

uv vs pip + venv vs Poetry vs PDM vs Hatch (summary) ​

Pick uv when you want one fast tool for interpreters, environments, locking and running; pick pip + venv when you cannot install anything else (a minimal CI image, a teaching environment, the plain-venv lab in this chapter); pick Poetry or PDM when a team already relies on their lockfiles and plugins; pick Hatch for library builds with matrix environments; ignore Rye (discontinued). The decision is cheap to reverse because [project] is standard: switching tools mostly changes the lock.

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One repository, one pyproject.toml, one uv.lock, one Dockerfile. uv sync on a laptop, uv sync --locked --no-dev in the image, uv run uvicorn ... (see FastAPI in Production) in dev. The snippet project is this shape: a single package, a SQLite database, tests that run in 0.08 s.

Modular monolith and multiple databases ​

Inside one deployable, split by packages under src/ (see APIRouter & Project Structure) and enforce boundaries with Ruff's import rules (for example TID banned-api or per-package per-file-ignores; not run here). Extras express optional modules (inventory-tool[api]); groups express developer-only tools. Several databases mean several settings objects, still read from one environment.

Microservices ​

Each service is its own project (own pyproject.toml, own lock, own image) or a member of a uv workspace that shares one lock and builds different images with --package. What does not survive a service boundary is a shared virtual environment: every service pins its own libraries, so a shared library (models, client SDKs) is published as a versioned package or kept in the workspace and consumed with { workspace = true }.

     multi-service repository with a workspace (illustrative; not run)
1    repo/pyproject.toml           [tool.uv.workspace] members = ["services/*", "libs/*"]
2    repo/uv.lock                  one lock, one set of versions for every service
3    services/orders/Dockerfile    uv sync --locked --no-dev --package orders --no-editable
4    services/billing/Dockerfile   uv sync --locked --no-dev --package billing --no-editable
5    libs/events/                  shared package, built into both images

Distributed data: replicas, caches, sharded databases, multi-region ​

Tooling touches distributed systems in one way: every replica of a service must run the same dependency set. The image built from uv.lock is the unit of deployment; the lock hash and the image digest together answer "which versions are running in region B". A cache layer (Redis) or a replica database changes nothing in pyproject.toml; the settings (URLs, timeouts) come from the environment (.env locally, platform variables in production).

Scaling path: 1×, 10×, 100× ​

ScaleTooling shape
1× (one developer)uv init, uv add, uv run, Ruff in the editor
10× (a team)Commit uv.lock; CI with --locked; pre-commit; Makefile/justfile; Dockerfile with a cached dependency layer
100× (many services, many teams)Workspace or internal package index, pinned uv/Ruff versions in a shared CI template, uv export with hashes for audited deployments, dependency update bot, a documented Python support window

Lab ​

Each step is labelled real (run on 2026-11-29; transcripts in pipeline/sources/python-tooling-uv-ruff-venv/runs/) or expected, not run. Run all commands from docs/snippets/python/python-tooling-uv-ruff-venv. To keep the repository clean, set UV_PROJECT_ENVIRONMENT outside it first (a real .venv here would not be git-ignored at the repository level).

1. Plain venv and pip: the tests run without uv (real) ​

bash
python3 -m venv /tmp/plain                       # pip 21.2.4, setuptools 58.0.4 are seeded
/tmp/plain/bin/python -m pip install -U pip      # -> pip 26.0.1
cd <copy of the project> && /tmp/plain/bin/python -m pip install -e ".[test]"
/tmp/plain/bin/python -m pytest
# Successfully installed exceptiongroup-1.3.2 iniconfig-2.1.0 inventory-tool-0.1.0 packaging-26.3 pluggy-1.6.0
#   pygments-2.21.0 pytest-8.4.2 python-dotenv-1.2.1 tomli-2.5.0 typing-extensions-4.16.0
# collected 18 items
# tests/test_cli.py ....   tests/test_db.py .....   tests/test_environment.py .........
# ============================== 18 passed in 0.08s ==============================
/tmp/plain/bin/inventory-report --no-env-file
# sku      qty  name
# GM-001     0  Catan
# BK-002     3  Designing Data-Intensive Applications
# -- 2 product(s) below 5

2. Look inside the environment (real) ​

bash
cat /tmp/plain/pyvenv.cfg
# home = /Library/Developer/CommandLineTools/usr/bin
# include-system-site-packages = false
# version = 3.9.6
/tmp/plain/bin/python -c "import sys; print(sys.prefix); print(sys.base_prefix)"
PYTHONPATH=/tmp/x /tmp/plain/bin/python    -c "import sys; print(sys.path[:3])"   # ['', '/tmp/x', '.../python39.zip']
PYTHONPATH=/tmp/x /tmp/plain/bin/python -I -c "import sys; print(sys.path[:3])"   # no '' and no '/tmp/x'

3. Lock, sync, run with uv (real) ​

bash
export UV_PROJECT_ENVIRONMENT=/tmp/inventory-venv UV_PYTHON_DOWNLOADS=never
uv lock            # Resolved 44 packages in 5.67s   (second run: Resolved 44 packages in 2ms)
uv sync            # Creating virtual environment ...; Prepared 15 packages in 2.51s; Installed 15 packages in 16ms
uv run pytest      # 18 passed in 0.08s
uv run inventory-report --no-env-file
uv tree --no-dev --depth 1
# inventory-tool v0.1.0
# ├── python-dotenv v1.2.1
# ├── tomli v2.5.0
# ├── fastapi v0.128.8 (extra: api)
# ├── packaging v26.3 (extra: test)
# └── pytest v8.4.2 (extra: test)

4. Add, remove, and the lock guards (real) ​

bash
uv add httpx                 # Resolved 49 packages in 2.08s ... + httpx==0.28.1; pyproject gains "httpx>=0.28.1"
uv add --dev pytest-cov      # + pytest-cov==7.1.0, coverage==7.10.7
uv add --optional api uvicorn
uv remove httpx              # Uninstalled 16 packages (httpx and what only it needed)
uv lock --check              # Resolved 54 packages in 2ms  (exit 0)
# edit pyproject.toml: add "rich>=13" and DO NOT lock
uv sync --locked
# error: The lockfile at `uv.lock` needs to be updated, but `--locked` was provided.
#   cause: Requirements for `inventory-tool==0.1.0` differ; added: rich>=13
# hint: To update the lockfile, run `uv lock`.

5. Export and extras (real) ​

bash
uv export --no-dev --no-hashes --no-emit-project     # three lines of pins with markers, see Lockfiles
uv export --no-dev --no-emit-project                 # the same with --hash=sha256:... continuations
uv sync --locked --no-dev                            # from the full dev environment: Uninstalled 14 packages
uv sync --frozen --no-default-groups --group lint    # then: + ruff==0.17.6 (the real transcript's order)

6. Ruff on the messy file (real) ​

bash
uv run ruff check .                                         # All checks passed!
uv run ruff check lint_demo/messy.py --output-format concise   # Found 9 errors. [*] 4 fixable (3 unsafe)
uv run ruff check --fix lint_demo/messy.py                  # Found 9 errors (4 fixed, 5 remaining)
uv run ruff format --diff lint_demo/messy.py                # one line reformatted
uv run mypy                                                 # Success: no issues found in 5 source files

Do this in a copy: --fix rewrites the file. (The page's real transcripts were produced in a scratch copy.)

7. A script with inline metadata, and tools (real) ​

bash
uv run scripts/where_am_i.py       # runs in a cached environment: "in a venv  : True", dotenv from .../uvcache/environments-v2/...
uvx ruff --version                 # ruff 0.17.6
uv venv /tmp/venv-demo             # pyvenv.cfg has uv = 0.13.10; no pip inside

8. Not run here (expected) ​

bash
uv python install 3.13                      # downloads a managed CPython
docker build -t inventory-tool .            # the multi-stage image
docker run --rm inventory-tool              # prints the two-row report
pre-commit install && pre-commit run --all-files
uv export --no-dev --no-emit-project -o requirements.txt && pip install --require-hashes -r requirements.txt

For PHP/Laravel developers ​

The mental map (Composer's vendor directory is the closest thing to .venv): composer.json is pyproject.toml (require is [project] dependencies, require-dev is a dependency group), composer.lock is uv.lock, vendor/ is .venv, composer install is uv sync, composer require is uv add. The one concept Composer does not have is the virtual environment as a separate step: Composer always installs into the project's vendor/, so there is no "which environment am I in" question. Composer's docs: "Committing this file to version control is important because it will cause anyone who sets up the project to use the exact same versions of the dependencies that you are using", the same rule as for uv.lock. Laravel Pint is "an opinionated PHP code style fixer" that is "built on top of PHP CS Fixer", and plays the role of ruff format plus the style half of ruff check; static analysis (PHPStan, Larastan) plays the role of mypy.

php
// config/inventory.php (Laravel 13): the Python Settings dataclass in config.py
return [
    'database_path' => env('INVENTORY_DB', ':memory:'),           // os.environ / .env, same precedence idea
    'low_stock_threshold' => (int) env('LOW_STOCK_THRESHOLD', 5), // int(merged.get("LOW_STOCK_THRESHOLD", "5"))
];
Laravel / PHPPython
composer.json require[project] dependencies
composer.json require-dev[dependency-groups] dev (PEP 735)
composer.lockuv.lock
vendor/.venv/ (and site-packages inside it)
composer installuv sync
composer install --no-devuv sync --no-dev
composer require monolog/monologuv add httpx
composer update vendor/pkguv lock --upgrade-package pkg
^1.2.3 = >=1.2.3 <2.0.0>=1.2.3,<2 (no caret in PEP 440)
~1.2.3 = >=1.2.3 <1.3.0~=1.2.3 (compatible release, similar meaning)
composer run-script testuv run pytest, Makefile, justfile
composer global require / phar toolsuvx / uv tool install
vendor/bin/pintuv run ruff format .
PHP-CS-Fixer rule setsRuff rule selection (select = [...])
php artisan serveuv run fastapi dev (see the pilot)
.env read by env().env read by python-dotenv or pydantic-settings
php -v and the OS PHP.python-version, uv python

The Go angle ​

Go folds interpreters, environments and locks into the toolchain: a module is the unit, go.mod lists requirements ("A require directive declares a minimum required version"), go.sum holds hashes ("checksums of modules you depend on ... to verify the integrity of downloaded module files"), downloads live in one module cache, and builds are static binaries, so there is no environment to activate and no runtime to install on the server. The twin chapters are Toolchain, Modules & Packages and Project Layout, golangci-lint, Makefile, Docker & Multi-Binary Builds. "Gofmt is a tool that automatically formats Go source code" and has no options to argue about; Python's equivalent is ruff format with its few settings; go vet "examines Go source code and reports suspicious constructs", the role of ruff check (bugbear and Pyflakes) and mypy together.

go
// internal/config/config.go: the Go counterpart of src/inventory/config.py
package config

import (
	"os"
	"strconv"
)

type Settings struct {
	DatabasePath      string
	LowStockThreshold int
}

func Load() Settings {
	s := Settings{DatabasePath: ":memory:", LowStockThreshold: 5}
	if v := os.Getenv("INVENTORY_DB"); v != "" {
		s.DatabasePath = v
	}
	if v, err := strconv.Atoi(os.Getenv("LOW_STOCK_THRESHOLD")); err == nil {
		s.LowStockThreshold = v
	}
	return s // a .env file needs a library (godotenv) in Go too; the standard library reads only the environment
}
ConcernPython (uv)Go
Declarationpyproject.tomlgo.mod
Lockuv.lock (universal, hashes)go.sum (checksums) plus minimal version selection
Install location.venv/lib/pythonX.Y/site-packagesthe module cache; build output is a binary
Version of the languagerequires-python, .python-versionthe go directive in go.mod
Selection ruleresolver picks the highest compatible versions"minimal version selection (MVS)"
Formatruff formatgofmt
Lintruff check, mypygo vet, golangci-lint
Run toolsuvx, uv toolgo run pkg@version (not run here)
Shipimage with .venva static binary in a small image

Common misconceptions ​

BeliefReality
python and python3 are the same everywherePEP 394: some systems provide no python; here python was "not found"
I must activate the venv to use itCall .venv/bin/python or uv run; activation edits PATH only
A venv is a copy of PythonA directory with pyvenv.cfg pointing at the base (home = ...) and its own site-packages
pyproject.toml pins versionsIt declares ranges; the lock pins
Extras and dependency groups are the sameExtras ship in the wheel; groups (PEP 735) "are not included in any built distribution"
~= is npm's ~~=1.4.2 is >=1.4.2, ==1.4.*; ~=1.4 is >=1.4, ==1.*
uv.lock is Linux-only or machine-specificIt is universal: markers per Python version and platform (4 resolution-markers in the real lock)
uv sync only adds packagesIt is exact: it removes what the lock does not contain (14 uninstalled)
uv venv installs pipIt does not; --seed opts in
Ruff only formatsruff check is the linter; ruff format is the formatter; two commands
ruff check --fix fixes everything safelyUnsafe fixes need --unsafe-fixes and can leave wrong code (the list[str] = None result)
.env is production configurationIt is a development convenience; real environment variables win
src layout is required to publishIt is a recommendation: it prevents importing the working directory by accident
--frozen and --locked are interchangeable--locked fails on a stale lock; --frozen does not check
Rye is the Astral project managerRye is discontinued (February 2025); use uv

Cheat sheet ​

TopicWhat to remember
Create a projectuv init NAME (src layout, .python-version, build backend)
Add / removeuv add PKG, uv add --dev PKG, uv add --optional EXTRA PKG, uv remove PKG
Environment from the lockuv sync (exact), uv sync --locked in CI
Run somethinguv run CMD, uv run --with PKG CMD, uvx TOOL
Lockuv lock, uv lock --check, uv lock --upgrade-package P
Production installuv sync --locked --no-dev --no-editable
Docker layersdeps layer: --no-install-project; env: UV_COMPILE_BYTECODE=1, UV_LINK_MODE=copy
Versionsrequires-python, .python-version, uv python install/pin/find
Specifiers>=1,<2 range; ~=1.4.2 compatible; ; python_version < '3.11' marker
Extras vs groupsextras ship ([project.optional-dependencies]); groups do not ([dependency-groups])
Scripts# /// script block, uv run file.py, uv lock --script
Ruffruff check --fix . then ruff format .; CI: ruff check . and ruff format --check .
Rule setsselect = ["E", "F", "I", "UP", "B"], ignore = ["E501"], per-file-ignores
Exportuv export --no-dev --no-emit-project, with hashes for pip --require-hashes
Layoutsrc/<package>/ + tests/; editable install for development
Config.env.example committed, .env ignored, real env wins
Debug the environmentsys.prefix vs sys.base_prefix, python -m site, python -I
EquivalentsComposer: composer.lock / vendor/; Go: go.sum / module cache

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What is a virtual environment, and what does pyvenv.cfg contain? Must-know ​

Answer

Answer: A directory with its own lib/pythonX.Y/site-packages, a bin/python that points at the base interpreter, and a pyvenv.cfg with home (the base interpreter's directory), include-system-site-packages = false and the version. Inside it sys.prefix is the environment and sys.base_prefix the base installation. It is not a copy of Python. Activation is optional: .venv/bin/python and uv run work without it.

2 — Why does python3 -c "import inventory" fail outside the environment even though the project exists? Must-know ​

Answer

Answer: With a src layout the package directory is src/inventory, which is not on sys.path for the system interpreter, and the project is not installed there. Inside the environment the editable install adds a .pth entry for src/. Run it with uv run python ... or the venv's interpreter. (Real: ModuleNotFoundError: No module named 'inventory' from the system python3.)

3 — What is the difference between [project.optional-dependencies] and [dependency-groups]? Must-know ​

Answer

Answer: Extras (PEP 621) are part of the built package's metadata and users can ask for them (pip install "pkg[api]"). Dependency groups (PEP 735) are "not included in any built distribution" and are for developers (uv sync --group lint, --no-dev). Use extras for optional product features and groups for tests, linters and docs.

4 — What do ~=1.4.2, >=1.0,<2 and tomli>=2.0; python_version < '3.11' mean? Must-know ​

Answer

Answer: ~=1.4.2 is the PEP 440 compatible release: >=1.4.2, ==1.4.*. >=1.0,<2 accepts 1.0 up to any 1.x (comma means AND). The third installs tomli only where the PEP 508 marker is true, i.e. on Python older than 3.11. There is no caret operator in PEP 440; Composer and Poetry carets are different.

5 — pyproject.toml already lists dependencies. Why commit uv.lock too? Must-know ​

Answer

Answer: pyproject.toml has ranges; the lock has the exact resolved versions, hashes and markers, so every machine and CI installs the same set. uv's lock is universal (all Python versions and platforms), human-readable TOML, managed by uv and not edited by hand. Commit both; install with uv sync --locked.

6 — What is the difference between uv sync, uv run and uv lock? Important ​

Answer

Answer: uv lock only resolves and writes uv.lock. uv sync makes .venv match the lock exactly (it also removes extra packages: 14 were uninstalled in the real run). uv run CMD locks and syncs inexactly if needed, then runs the command in the environment. --locked makes any of them fail on a stale lock; --frozen skips the check.

7 — How do you keep pytest and ruff out of the production image? Important ​

Answer

Answer: Put them in a dependency group (dev), then build with uv sync --locked --no-dev (plus --no-install-project for the cached dependency layer and --no-editable for the project), in a multi-stage build that copies only .venv to the runtime stage. Set UV_COMPILE_BYTECODE=1 for faster starts.

8 — Which Ruff rule families does this chapter select, and what does each do? Important ​

Answer

Answer: E (pycodestyle errors), F (Pyflakes: unused imports and names), I (isort import order), UP (pyupgrade: modern syntax for the target-version), B (bugbear: likely bugs such as mutable defaults). E501 is ignored because ruff format owns line length. ruff check lints; ruff format formats; --fix applies safe fixes only.

9 — Why did ruff check not flag Optional[str] in the demo file, and what changes with target-version = "py310"? Important ​

Answer

Answer: target-version = "py39" means str | None is not allowed at runtime on the oldest supported Python, so UP045 stays quiet. With --target-version py310 the real run reported UP045 Use X | None for type annotations. Rule behaviour follows the declared target, so set it to your real minimum.

10 — A teammate runs uv add offline and edits pyproject.toml by hand elsewhere. How does CI notice a stale lock? Important ​

Answer

Answer: CI runs uv sync --locked. If pyproject.toml and uv.lock disagree it fails with error: The lockfile at uv.lock needs to be updated, but --locked was provided. and a cause: line naming the differing requirement (real output: added: rich>=13). Fix: run uv lock and commit.

11 — When would you choose a src layout over a flat layout? Good to know ​

Answer

Answer: For libraries and services with a test suite. The packaging guide says the src layout "helps prevent accidental usage of the in-development copy of the code" because the working directory is first on the import path. The cost is an installation step (editable for development). uv init generates src/<name>/ by default.

12 — How should configuration reach a Python service in development and in production? Good to know ​

Answer

Answer: Development: a .env file (ignored by Git; .env.example committed) read by python-dotenv or pydantic-settings. Production: real environment variables set by the platform. Real variables must win over the file: python-dotenv does not override by default, pydantic-settings documents environment first, and the snippet merges {**file_values, **os.environ}.

Glossary ​

TermMeaning
CPythonThe reference Python interpreter, implemented in C
python.org installersOfficial installers for specific Python versions
pyenvVersion manager that switches interpreters through shims on PATH
uv python installDownloads a uv-managed interpreter
python3 vs pythonThe command names PEP 394 describes; python may not exist
PEP 394The "python" command on Unix-like systems
virtual environmentA directory with pyvenv.cfg and its own site-packages for one project
venvThe standard-library module that creates virtual environments (python -m venv)
virtualenvThe third-party predecessor/superset tool
uv venvuv's environment creator; no pip by default
site-packagesThe directory where installed packages live
sys.pathThe list of directories Python searches for imports
sys.prefix / sys.base_prefixThe environment root and the base installation root
-I (isolated mode)Ignores PYTHON* variables, the script directory and the user site
activateA shell script that edits PATH and the prompt; optional
pyproject.tomlThe project's declaration file (build system, metadata, tool settings)
PEP 621Standard [project] metadata
project metadataname, version, requires-python, dependencies, scripts
dependenciesRuntime requirements in [project]
optional-dependencies / extrasOptional feature sets that ship with the package
dependency groups (PEP 735)Local requirement lists not published with the package
[build-system]requires and build-backend for building (PEP 517/518)
hatchlingThe Hatch project's build backend
setuptoolsThe long-standing build backend
tool tables[tool.<name>] sections owned by individual tools
uvA single binary for interpreters, environments, locking, running and tools
uv init / add / removeCreate a project / add or drop a dependency
uv sync / uv lock / uv runInstall the lock / resolve / run in the environment
uv pythonInterpreter management subcommands
uvx / uv toolRun or install tools in isolated environments
uv pippip-compatible commands inside uv
uv workspaceSeveral packages sharing one lock ([tool.uv.workspace])
inline script metadata (PEP 723)A # /// script comment block with dependencies for a single file
uv cacheGlobal store of downloaded and built packages, linked into environments
pipThe standard installer
pip-tools / pip-compilePins requirements.in into a platform-specific requirements.txt
Poetry / PDM / Rye / HatchOther project managers; Rye is discontinued
lockfile / uv.lockExact resolved versions, hashes and markers, committed to Git
requirements.txt / uv exportpip's file format and the uv command that writes it from the lock
reproducible installsThe same versions and files on every machine
hashesSHA-256 digests; pip --require-hashes refuses mismatches
platform markers / environment markers (PEP 508)Conditions such as python_version < '3.11'
PEP 440Version identification and specifiers
version specifiers==, >=, <, ~=, !=, .*
pin vs rangeExact version vs accepted interval
caret vs tilde^ and ~ in Composer and Poetry; PEP 440 only has ~=
RuffLinter and formatter in one binary
ruff check / ruff formatLint (with --fix) / format (with --check)
rule selectionselect, ignore and prefixes such as E, F, I, UP, B
isort rules / pyupgrade rulesRule families I and UP
line-lengthWidth shared by the formatter and E501
per-file-ignoresRules disabled for matching paths
pre-commitGit hook framework that runs Ruff before commits
Black compatibilityRuff's formatter emits near-identical Black output
mypy / pyrightStatic type checkers
pytest as a toolThe test runner, in the dev group
task runneruv run, Makefile, justfile, taskipy
--no-devSkip the default dev group when syncing
UV_COMPILE_BYTECODECompile .pyc files at install time
multi-stage buildA builder image whose .venv is copied into a smaller runtime image
astral-sh/setup-uvThe GitHub Action that installs uv and caches it
src layout / flat layoutPackage under src/ vs in the repository root
.env / python-dotenv / pydantic-settingsLocal variable file, its loader, and the typed settings library
Composer, composer.lock, vendor/PHP's package manager, its lock and install directory
Pint / PHP-CS-FixerPHP code style fixers
go.mod / go.sumGo module requirements and checksums
gofmt / go vetGo's formatter and static checker

References ​

All URLs were fetched on 2026-11-29 and returned 200 (pipeline/sources/python-tooling-uv-ruff-venv/manifest.tsv; saved text in the same directory; the real-run transcripts are in runs/). The pyright documentation site is JavaScript-rendered, so its text was taken from GitHub instead.

SourceURLSaved as
uv: installationhttps://docs.astral.sh/uv/getting-started/installation/uv-getting-started.txt
uv: working on projectshttps://docs.astral.sh/uv/guides/projects/uv-guide-projects.txt
uv: project layout, lockfile, .venvhttps://docs.astral.sh/uv/concepts/projects/layout/uv-concepts-projects-layout.txt
uv: managing dependencies (groups, extras)https://docs.astral.sh/uv/concepts/projects/dependencies/uv-concepts-projects-deps.txt
uv: locking and syncinghttps://docs.astral.sh/uv/concepts/projects/sync/uv-concepts-projects-sync.txt
uv: creating projects (uv init)https://docs.astral.sh/uv/concepts/projects/init/uv-concepts-projects-init.txt
uv: running commands (uv run)https://docs.astral.sh/uv/concepts/projects/run/uv-concepts-projects-run.txt
uv: configuring projectshttps://docs.astral.sh/uv/concepts/projects/config/uv-concepts-projects-config.txt
uv: workspaceshttps://docs.astral.sh/uv/concepts/projects/workspaces/uv-concepts-workspaces.txt
uv: Python versionshttps://docs.astral.sh/uv/concepts/python-versions/uv-concepts-python-versions.txt
uv: tools (uvx)https://docs.astral.sh/uv/concepts/tools/uv-concepts-tools.txt
uv: cachinghttps://docs.astral.sh/uv/concepts/cache/uv-concepts-cache.txt
uv: resolution (universal vs platform-specific)https://docs.astral.sh/uv/concepts/resolution/uv-concepts-resolution.txt
uv: using uv in Dockerhttps://docs.astral.sh/uv/guides/integration/docker/uv-guide-docker.txt
uv: using uv in GitHub Actionshttps://docs.astral.sh/uv/guides/integration/github/uv-guide-github.txt
uv: running scriptshttps://docs.astral.sh/uv/guides/scripts/uv-guide-scripts.txt
uv: compatibility with pip and pip-toolshttps://docs.astral.sh/uv/pip/compatibility/uv-pip-compat.txt
uv: pip interface environmentshttps://docs.astral.sh/uv/pip/environments/uv-pip-environments.txt
uv: settings referencehttps://docs.astral.sh/uv/reference/settings/uv-reference-settings.txt
uv: environment variableshttps://docs.astral.sh/uv/reference/environment/uv-reference-envvars.txt
uv: pre-commit integrationhttps://docs.astral.sh/uv/guides/integration/pre-commit/uv-pre-commit.txt
Ruff: tutorialhttps://docs.astral.sh/ruff/tutorial/ruff-tutorial.txt
Ruff: ruleshttps://docs.astral.sh/ruff/rules/ruff-rules.txt
Ruff: configurationhttps://docs.astral.sh/ruff/configuration/ruff-configuration.txt
Ruff: the formatterhttps://docs.astral.sh/ruff/formatter/ruff-formatter.txt
Ruff: the linterhttps://docs.astral.sh/ruff/linter/ruff-linter.txt
Ruff: known deviations from Blackhttps://docs.astral.sh/ruff/formatter/black/ruff-black.txt
Ruff: integrations (pre-commit)https://docs.astral.sh/ruff/integrations/ruff-integrations.txt
Ruff: FAQhttps://docs.astral.sh/ruff/faq/ruff-faq.txt
Python: venv modulehttps://docs.python.org/3/library/venv.htmlpy-library-venv.txt
Python tutorial: virtual environments and packageshttps://docs.python.org/3/tutorial/venv.htmlpy-tutorial-venv.txt
Python: command line (-I isolated mode)https://docs.python.org/3/using/cmdline.htmlpy-cmdline.txt
Python: site modulehttps://docs.python.org/3/library/site.htmlpy-library-site.txt
Python: sys.path initializationhttps://docs.python.org/3/library/sys_path_init.htmlpy-library-sys-path.txt
PyPA: pyproject.toml specificationhttps://packaging.python.org/en/latest/specifications/pyproject-toml/pkg-pyproject-spec.txt
PyPA: dependency specifiershttps://packaging.python.org/en/latest/specifications/dependency-specifiers/pkg-dep-specifiers.txt
PyPA: version specifiershttps://packaging.python.org/en/latest/specifications/version-specifiers/pkg-version-specifiers.txt
PyPA: dependency groups specificationhttps://packaging.python.org/en/latest/specifications/dependency-groups/pkg-dependency-groups.txt
PyPA: inline script metadatahttps://packaging.python.org/en/latest/specifications/inline-script-metadata/pkg-inline-metadata.txt
PyPA: writing your pyproject.tomlhttps://packaging.python.org/en/latest/guides/writing-pyproject-toml/pkg-writing-pyproject.txt
PyPA: src layout vs flat layouthttps://packaging.python.org/en/latest/discussions/src-layout-vs-flat-layout/pkg-src-layout.txt
PyPA: tool recommendationshttps://packaging.python.org/en/latest/guides/tool-recommendations/pkg-tool-recs.txt
PEP 394: the "python" commandhttps://peps.python.org/pep-0394/pep-394.txt
PEP 440: version identificationhttps://peps.python.org/pep-0440/pep-440.txt
PEP 508: dependency specificationhttps://peps.python.org/pep-0508/pep-508.txt
PEP 517: build backendshttps://peps.python.org/pep-0517/pep-517.txt
PEP 518: pyproject.toml build-systemhttps://peps.python.org/pep-0518/pep-518.txt
PEP 621: project metadatahttps://peps.python.org/pep-0621/pep-621.txt
PEP 723: inline script metadatahttps://peps.python.org/pep-0723/pep-723.txt
PEP 735: dependency groupshttps://peps.python.org/pep-0735/pep-735.txt
pip: requirements file formathttps://pip.pypa.io/en/stable/reference/requirements-file-format/pip-requirements-format.txt
pip: secure installs, hash-checking modehttps://pip.pypa.io/en/stable/topics/secure-installs/pip-hash-checking.txt
pip-toolshttps://pip-tools.readthedocs.io/en/stable/pip-tools.txt
Poetry: documentationhttps://python-poetry.org/docs/poetry-docs.txt
PDM: documentationhttps://pdm-project.org/latest/pdm-docs.txt
Hatch: documentationhttps://hatch.pypa.io/latest/hatch-docs.txt
pyenv READMEhttps://raw.githubusercontent.com/pyenv/pyenv/master/README.mdpyenv-readme.txt
pre-commithttps://pre-commit.com/precommit.txt
setup-uv READMEhttps://raw.githubusercontent.com/astral-sh/setup-uv/main/README.mdsetup-uv-readme.txt
python-dotenv READMEhttps://raw.githubusercontent.com/theskumar/python-dotenv/main/README.mddotenv-readme.txt
Pydantic: settings managementhttps://docs.pydantic.dev/latest/concepts/pydantic_settings/pydantic-settings.txt
Composer: basic usagehttps://getcomposer.org/doc/01-basic-usage.mdcomposer-basic.txt
Laravel Pinthttps://laravel.com/docs/13.x/pintlaravel-pint.txt
Go: modules referencehttps://go.dev/ref/modgo-ref-mod.txt
Go: managing dependencieshttps://go.dev/doc/modules/managing-dependenciesgo-managing-deps.txt
PHP-CS-Fixer READMEhttps://raw.githubusercontent.com/PHP-CS-Fixer/PHP-CS-Fixer/master/README.mdphp-cs-fixer.txt
mypy: documentationhttps://mypy.readthedocs.io/en/stable/mypy-docs.txt
pytest: documentationhttps://docs.pytest.org/en/stable/pytest-docs.txt
Hatch: build configurationhttps://hatch.pypa.io/latest/config/build/hatchling-docs.txt
setuptools: pyproject.toml configurationhttps://setuptools.pypa.io/en/latest/userguide/pyproject_config.htmlsetuptools-pyproject.txt
Poetry: dependency specificationhttps://python-poetry.org/docs/dependency-specification/poetry-dependency-spec.txt
Rye: documentation (discontinued)https://rye.astral.sh/rye-docs.txt
uv: documentation homehttps://docs.astral.sh/uv/uv-index.txt
Composer: versions and constraintshttps://getcomposer.org/doc/articles/versions.mdcomposer-versions.txt
PEP 751: pylock.tomlhttps://peps.python.org/pep-0751/pep-751.txt
Go blog: gofmthttps://go.dev/blog/gofmtgo-blog-gofmt.txt
Go: cmd/vet documentationhttps://go.dev/src/cmd/vet/doc.gogo-vet-doc.txt
uv: using uv with FastAPIhttps://docs.astral.sh/uv/guides/integration/fastapi/uv-guide-integration-fastapi.txt
python.org: downloadshttps://www.python.org/downloads/python-downloads.txt
Hatch: why Hatchhttps://hatch.pypa.io/latest/why/pyproject-guide-hatch.txt
virtualenv: documentationhttps://virtualenv.pypa.io/en/latest/virtualenv-docs.txt
uv: CLI referencehttps://docs.astral.sh/uv/reference/cli/uv-reference-cli.txt
pip: install referencehttps://pip.pypa.io/en/stable/cli/pip_install/pip-install-ref.txt
Ruff: settings referencehttps://docs.astral.sh/ruff/settings/ruff-settings.txt
taskipy READMEhttps://raw.githubusercontent.com/taskipy/taskipy/master/README.mdtaskipy-readme.txt
just READMEhttps://raw.githubusercontent.com/casey/just/master/README.mdjust-readme.txt
mypy: configuration filehttps://mypy.readthedocs.io/en/stable/config_file.htmlmypy-config-file.txt
pyright: configurationhttps://raw.githubusercontent.com/microsoft/pyright/main/docs/configuration.mdpyright-config.txt
pyright READMEhttps://raw.githubusercontent.com/microsoft/pyright/main/README.mdpyright-readme.txt

Built by Morteza Negahi