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,
venvmodule, 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 for | Go to |
|---|---|
| The tables you can memorise in one minute | Everything in one minute |
| Why Python projects need this much tooling | Why it exists |
| Python 2 to uv: a timeline | Where it comes from |
| The snippet project, before and after | Python |
Which python, python3, which version | Interpreters |
| What a virtual environment really is | Virtual environments |
venv, virtualenv, uv venv | venv vs virtualenv vs uv venv |
[project], extras, groups, [tool.*] | pyproject.toml |
>=, ~=, ==, markers | Version specifiers and markers |
uv init, uv add, uv sync, uv run | uv projects |
uv python install, .python-version | uv python |
uvx, uv tool | Tools: uvx |
| A single file with its own dependencies | Inline script metadata |
uv pip install, uv pip compile | The pip interface |
| Several packages in one repository | Workspaces |
| Why uv is fast, where packages are stored | The cache |
uv.lock, requirements.txt, hashes | Lockfiles |
| pip, pip-tools, Poetry, PDM, Rye, Hatch | Choosing a tool |
ruff check, rule codes, ruff format | Ruff |
| pre-commit, Black compatibility | Ruff in the workflow |
| mypy and pyright | Type checking preview |
| pytest, Makefile, justfile | Tests and tasks |
src/ or flat | Project layout |
.env, python-dotenv, pydantic-settings | Configuration and .env |
| Dockerfile with uv | Docker |
| GitHub Actions with uv | CI |
| Exact messages and commands | Mechanics |
Composer, Pint, go.mod, gofmt | For PHP/Laravel developers, The Go angle |
Everything in one minute
The four layers. Each row is unpacked in the concept catalogue.
| Layer | What it is | Plain words | Where it lives |
|---|---|---|---|
| Interpreter | CPython (or PyPy …) at a version | "The program that runs .py files" | /usr/bin/python3, python.org installer, pyenv shim, uv-managed build |
| Environment | A directory with its own site-packages and a pyvenv.cfg | "A private shelf of libraries for one project" | .venv/ next to pyproject.toml |
| Declaration | pyproject.toml | "What the project wants: ranges, extras, groups, tool settings" | repository root |
| Lock | uv.lock or hashed requirements.txt | "What was actually chosen: exact versions, hashes, markers" | repository root, committed |
The commands you will type daily.
| Command | Does | Edits |
|---|---|---|
uv init | Creates pyproject.toml, .python-version, src/<name>/ | files |
uv add httpx / uv remove httpx | Edits [project] dependencies, re-locks, syncs | pyproject.toml, uv.lock, .venv |
uv add --dev pytest | Adds to the dev dependency group | same |
uv add --optional api uvicorn | Adds to an extra | same |
uv lock | Re-resolves, writes uv.lock | uv.lock |
uv sync | Makes .venv match the lock exactly | .venv |
uv run <cmd> | Locks and syncs if needed, runs inside .venv | maybe all three |
uv python install 3.13 | Downloads a managed interpreter | uv's data directory |
uvx ruff check . | Runs a tool in a temporary environment | cache only |
uv export | Writes requirements.txt from the lock | stdout |
Ruff in one table.
| Concern | Command | Configured in |
|---|---|---|
| Find bugs and style problems | ruff check . | [tool.ruff.lint] select = ["E", "F", "I", "UP", "B"] |
| Fix the safe ones | ruff check --fix . | same; unsafe fixes need --unsafe-fixes |
| Format (Black-style) | ruff format . | [tool.ruff.format], line-length |
| Check in CI without writing | ruff format --check . | exit code non-zero |
| Sort imports | rule set I (isort) | [tool.ruff.lint.isort] |
| Modernise syntax | rule set UP (pyupgrade) | target-version |
Reproducibility in one table.
| Situation | Command | Why |
|---|---|---|
| New teammate | uv sync | Same versions as everybody |
| CI | uv sync --locked | Fail if pyproject.toml and uv.lock disagree |
| Docker, deps layer | uv sync --locked --no-install-project --no-dev | Cacheable layer without test tools |
| Legacy deploy tool | uv export --no-dev --no-emit-project > requirements.txt | pip can install it with --require-hashes |
| Upgrade one package | uv lock --upgrade-package httpx | Bump 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.
| Problem | What goes wrong without the tool | Which tool answers |
|---|---|---|
| Two projects, two versions of a library | One of them breaks after pip install -U | A virtual environment per project |
| "Works on my machine" | Teammate resolves >=2 to a newer release | A lockfile |
| Which Python? | The distro's python3 changes with an OS upgrade | .python-version, requires-python, uv python |
| Dev tools in production | The image ships pytest, ruff and mypy | Dependency groups, --no-dev |
| Slow installs | CI spends minutes in pip install | uv's cache, a cached Docker layer |
| Style arguments | Reviews about quotes and import order | One formatter, one linter, in pre-commit and CI |
The trade-off in one table.
| Simpler | More reproducible |
|---|---|
pip install -r requirements.txt into the global interpreter | Environment 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 CI | uv 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
- "A virtual environment is a copy of Python." It is a directory with a
pyvenv.cfgthat points at the base interpreter, a privatesite-packages, and apythonthat is usually a symlink to the base one. The real run below showshome = /Library/Developer/CommandLineTools/usr/bin. - "
pyproject.tomlpins my versions." It declares ranges. Without a lock, the nextpip install .can resolve to different versions; the lockfile is what pins. - "
uvis 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.
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:
[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:
"""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}))"""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"),
)"""`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:
-- 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):
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'")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:")"""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:
# /// 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-filerepos:
- 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"]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# Copy to .env (never commit .env). Real environment variables win over this file.
INVENTORY_DB=inventory.sqlite3
LOW_STOCK_THRESHOLD=5The 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
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 interpreterpython3 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.
| Source | Pros | Cons | Selected by |
|---|---|---|---|
OS Python (/usr/bin/python3) | Always there | Old (3.9.6 here), owned by the OS, may be externally managed | PATH |
| python.org installer | Official, several versions side by side | Manual install per machine | python3.12 on PATH, or full path |
| pyenv | Per-directory version via .python-version; compiles from source | Needs build dependencies; shims on PATH | pyenv local 3.12 |
uv python install | Prebuilt, fast, no compiler; managed by the same tool as the project | Another distribution source to trust | .python-version, requires-python, --python |
Docker python:3.12-slim | Exactly the version in production | Not for local editing | FROM 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).
| Fact | Where to see it | Real value here |
|---|---|---|
| Which environment am I in | sys.prefix != sys.base_prefix | True in the tests (test_tests_run_inside_a_venv) |
| Where packages go | lib/python3.9/site-packages | pip-21.2.4, setuptools-58.0.4 in a fresh plain venv |
| What the environment points at | pyvenv.cfg: home, include-system-site-packages, version | home = /Library/Developer/CommandLineTools/usr/bin |
What uv venv adds | uv = 0.13.10 and version_info = 3.9.6 keys; no pip | site-packages holds only _virtualenv.pth and _virtualenv.py |
| Which Python the entry point uses | first line of .venv/bin/inventory-report | the 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:
| Tool | Ships with | Installs pip | Interpreter selection | Typical command |
|---|---|---|---|---|
venv | CPython 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 run | python3 -m venv .venv |
virtualenv | pip package | Seeds packages (its docs have a "seeders" plugin point) | its own interpreter discovery (not exercised here) | virtualenv .venv |
uv venv | uv | No (opt in with --seed) | --python 3.12, .python-version, can download | uv venv |
uv sync | uv | No | requires-python + .python-version | creates .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.xshReal 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
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.
| Table | Standard | Purpose | Example from the snippet |
|---|---|---|---|
[build-system] | PEP 518 / 517 | How to build the project | requires = ["hatchling>=1.27"] |
[project] | PEP 621 | Metadata and runtime dependencies | requires-python = ">=3.9" |
[project.optional-dependencies] | PEP 621 | Extras (published) | api = ["fastapi>=0.115,<1"] |
[project.scripts] | PEP 621 | Console entry points | inventory-report = "inventory.cli:main" |
[dependency-groups] | PEP 735 | Local groups (never published) | lint = ["ruff>=0.8,<1"] |
[tool.hatch.build.targets.wheel] | Hatch | Where the package lives | packages = ["src/inventory"] |
[tool.uv] | uv | uv-only settings | default-groups = ["dev"] |
[tool.ruff] | Ruff | Linter and formatter | line-length = 88 |
[tool.pytest.ini_options] | pytest | Test discovery and options | testpaths = ["tests"] |
[tool.mypy] | mypy | Type checker settings | strict = 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:
| Mechanism | Defined in | Ships in the wheel | Installed by | Use for |
|---|---|---|---|---|
dependencies | PEP 621 | Yes (Requires-Dist) | always | what the code imports |
[project.optional-dependencies] (extras) | PEP 621 | Yes, with Provides-Extra | pip install ".[api]", uv sync --extra api | optional features: api, postgres |
[dependency-groups] | PEP 735 | No | uv 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.txt | pip format | n/a | pip install -r | exported lock, legacy |
[tool.poetry.dependencies] | Poetry before 2.0 | tool-specific | poetry install | older 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:
| Goal | Command | Edits |
|---|---|---|
| Add a runtime dependency | uv add httpx | dependencies (real: wrote "httpx>=0.28.1" first in the list) |
| Add to the dev group | uv add --dev pytest-cov | [dependency-groups] dev |
| Add to a named group | uv add --group lint ruff | [dependency-groups] lint |
| Add to an extra | uv add --optional api uvicorn | api = [...] (real: "uvicorn>=0.39.0") |
| Remove | uv remove httpx | pyproject, 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:
| Specifier | Meaning | Example | Matches |
|---|---|---|---|
==1.4.2 | exact | pytest==8.4.2 | only 8.4.2 |
==1.4.* | prefix match | ==1.4.* | 1.4.0, 1.4.9 |
>=1.0,<2 | range, comma = AND | python-dotenv>=1.0,<2 | 1.0 up to 1.x |
~=1.4.2 | compatible release | >=1.4.2, ==1.4.* | 1.4.9, not 1.5 |
!=1.5.0 | exclusion | requests>=2,!=2.30.0 | skips one release |
=== | arbitrary string equality | rare | avoid |
; python_version < '3.11' | PEP 508 environment marker | tomli>=2.0; python_version < '3.11' | tomli on 3.9/3.10 only |
[api,test] | extras of the dependency | inventory-tool[api,test]>=0.1 | parsed 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 variable | Meaning | Example |
|---|---|---|
python_version | 3.9-style major.minor | python_version < '3.11' |
python_full_version | 3.9.6 | uv writes python_full_version < '3.10' into uv.lock |
sys_platform | linux, darwin, win32 | pywin32; sys_platform == 'win32' |
platform_machine | arm64, x86_64 | wheels per architecture |
os_name | posix, nt | os_name == 'nt' |
extra | which extra is being installed | extra == '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".
| Style | Written as | Good for | Risk |
|---|---|---|---|
| Open lower bound | httpx>=0.28 | libraries | A breaking 1.0 lands unexpectedly |
| Bounded range | httpx>=0.28,<1 | libraries and apps with a lock | A bound that is too tight blocks upgrades |
| Compatible release | httpx~=0.28.1 | tools that follow patch releases | Meaning differs from npm, Composer, Poetry |
| Exact pin | httpx==0.28.1 | the lockfile, or examples (the FastAPI pilot pins) | Impossible to combine with others |
| Marker-gated | tomli>=2.0; python_version < '3.11' | backports | Marker 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 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:
| Command | What it does | Touches |
|---|---|---|
uv init NAME | New project. Real: .python-version (3.9), README.md, pyproject.toml, src/shop_api/; [project.scripts] and build-backend = "uv_build" | files |
uv init --lib NAME | Library template; real: src/shoplib/__init__.py plus py.typed | files |
uv add PKG | Add to dependencies, resolve, lock, sync | pyproject, lock, .venv |
uv add --dev / --group G / --optional E | Add to a group or an extra | same |
uv remove PKG | The reverse | same |
uv lock | Resolve only; --check verifies; --upgrade / --upgrade-package P bump | lock |
uv sync | Lock 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 CMD | Lock + sync (inexact), then run CMD in the environment; --with PKG adds a one-off dependency; --no-sync, --locked, --frozen | maybe all |
uv tree | Print the resolved dependency tree | none |
uv export | Write requirements.txt, pylock.toml (PEP 751) or CycloneDX output | stdout |
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").
| Flag | Meaning | Use in |
|---|---|---|
--locked | Error if uv.lock does not match pyproject.toml (same as uv lock --check) | CI, Docker final sync |
--frozen | Use uv.lock as is, no staleness check | Docker layer that has no pyproject.toml yet, offline use |
--no-sync | Do not touch the environment | scripted runs |
--no-dev / --no-default-groups | Skip the default dev group | production images |
--extra E / --group G | Include an extra or a group | feature builds, lint job |
--no-install-project | Install dependencies only | cacheable Docker layer |
--no-editable | Copy the project into site-packages | multi-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:
| Command | Does |
|---|---|
uv python list | Lists available and installed interpreters (--only-installed filters) |
uv python install 3.12 | Downloads a managed CPython (uv python install 3.12.3, '>=3.8,<3.10' also work per the docs) |
uv python find | Prints the interpreter uv would use |
uv python pin 3.12 | Writes .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 requestReal 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:
| Command | Persistence | Environment | Typical use |
|---|---|---|---|
uvx TOOL / uv tool run TOOL | none (cached) | temporary | one-off: uvx ruff format --check . |
uv tool install TOOL | installed | one per tool | daily tools; uv tool list, uv tool upgrade |
uv run --with PKG CMD | none | project env + extra package | try httpx==0.26.0 against the project |
pipx run / pipx install | equivalent idea | per tool | uv'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__.pyThe 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 / virtualenv | uv | Note |
|---|---|---|
python -m venv .venv | uv venv | no pip inside by default |
pip install -r requirements.txt | uv pip install -r requirements.txt | into the active venv |
pip freeze | uv pip freeze | same idea |
pip-compile requirements.in | uv pip compile requirements.in | by default "produces a resolution that is platform-specific, like pip-tools" |
pip-sync requirements.txt | uv pip sync requirements.txt | exact sync |
| (no equivalent) | uv lock / uv sync | universal 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 dependencyReal 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 packages | Resolved 44 packages in 5.67s |
Second uv lock on the same project | Resolved 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 cached | installs 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, copieduv 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-toolWithout --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".
| Format | Written by | Read by | Cross-platform | Hashes | Notes |
|---|---|---|---|---|---|
uv.lock | uv | uv only | yes (universal) | yes | "specific to uv" |
requirements.txt from uv export | uv | pip, uv pip, Docker legacy | yes, through markers per line | optional | for deploy tools that only know pip |
requirements.txt from pip-compile | pip-tools | pip | no (platform-specific) | optional (--generate-hashes) | "pip-tools = pip-compile + pip-sync" |
poetry.lock | Poetry | Poetry | not verified here | not verified here | tool-specific (Poetry's saved introduction only establishes repeatable installs) |
pdm.lock | PDM | PDM | not verified here | not verified here | tool-specific (its docs list "Lock Files") |
pylock.toml (PEP 751) | several tools | several | by design | yes | the standard; uv export supports it |
composer.lock | Composer | Composer | n/a | dist references | compare below |
go.sum | Go | Go | yes | checksums | compare 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):
| Tool | Creates envs | Locks | Manages Python versions | Reads [project] (PEP 621) | Notes |
|---|---|---|---|---|---|
| pip | no (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 does | no | yes (pip install ., --group) | the installer every other tool builds on |
| pip-tools | no | pip-compile writes pinned requirements.txt | no | yes | "pip-compile + pip-sync" |
| virtualenv / venv | yes | no | no | n/a | environment only |
| pyenv | no | no | yes (shims; compiles from source) | n/a | version management only |
| Poetry | yes | poetry.lock | no (not verified here) | from Poetry 2.0; before that [tool.poetry] | "Python dependency management and packaging made easy" |
| PDM | yes | pdm.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) |
| Hatch | yes (its docs list Environment, and "Dependency locker" among its plugin kinds) | via plugin, not the core workflow | not verified here | yes | also the home of the hatchling backend |
| Rye | yes | yes | yes | yes | discontinued February 2025; successor is uv |
| uv | yes | uv.lock | yes | yes | "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:
| Prefix | Origin | Catches | In the snippet |
|---|---|---|---|
E / W | pycodestyle | style and syntax: E711 == None, E722 bare except, E501 line too long | E selected, E501 ignored (the formatter owns line length) |
F | Pyflakes | unused imports and variables, undefined names | selected |
I | isort | import order and grouping (I001) | selected (isort rules) |
UP | pyupgrade | outdated syntax for the target version (UP035, UP006) | selected, depends on target-version = "py39" |
B | flake8-bugbear | likely bugs (B006, B017) | selected |
RUF | Ruff-specific | rules only Ruff has | default set; not selected explicitly here |
C90 | mccabe | complexity | not selected |
N | pep8-naming | naming | not selected |
S | flake8-bandit | security smells | not 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".
| Command | Does | Real result on messy.py |
|---|---|---|
ruff check . | Lint; exit code 1 if anything is found | All checks passed! on the project (the demo file is in extend-exclude) |
ruff check --fix | Apply safe fixes | Found 9 errors (4 fixed, 5 remaining) |
ruff check --fix --unsafe-fixes | Also apply unsafe fixes | Found 5 errors (4 fixed, 1 remaining); E722 (bare except) has no fix |
ruff check --statistics | Count findings per rule | 2 F401, 1 E722, 1 UP035, 1 E401, 1 B006, 1 UP006, 1 E711, 1 I001 |
ruff rule F401 | Explain a rule | prints "unused-import (F401)", "Derived from the Pyflakes linter" |
ruff check --select E,F,I,UP,B | Override the configured set for one run | same set as the config |
ruff check --add-noqa | Adds 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."
[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"| Setting | Meaning |
|---|---|
line-length | The formatter's target and the linter's E501 limit (88 is Black's default) |
target-version | Oldest Python the code must run on; controls UP rules and syntax checks |
src | Where first-party imports live, so I sorts inventory as first-party |
extend-exclude | Skip paths in addition to the defaults |
select / extend-select / ignore | Rule sets by prefix or code |
per-file-ignores | Rules to skip for matching paths, e.g. "tests/**" |
[tool.ruff.lint.isort] | known-first-party, combine-as-imports, section order |
# noqa: F401 | Suppress 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 reformattedReal 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.
| Question | Answer |
|---|---|
| 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)| Where | How | Gate? |
|---|---|---|
| Editor | Ruff language server / extension, format on save | no |
| pre-commit hook | .pre-commit-config.yaml | local only |
make lint / just lint | uv run ruff check . + uv run ruff format --check . | local, scriptable |
| CI job | same two commands | yes |
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.
| mypy | pyright | |
|---|---|---|
| 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 uv | uv run mypy | uvx pyright (not run) |
| In this snippet | yes (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.
| Runner | Syntax | Needs install | Pros | Cons |
|---|---|---|---|---|
uv run CMD | no file | uv | zero config, always the right environment | no composition |
| Makefile | target: + tab-indented recipes | make (present on most Unix) | universal, .PHONY | tabs, Windows friction |
| justfile | recipe: + indented body | just | no tab rule, recipe arguments, default: | another binary to install |
taskipy | [tool.taskipy.tasks] in pyproject.toml ("The complementary task runner for python") | pip package | stays in pyproject.toml | Python-only |
[project.scripts] | name = "pkg.mod:func" | none | real command on PATH of the environment | for 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:
| Flat | src | |
|---|---|---|
| Importable code | inventory/ in the root | src/inventory/ |
| Run without installing | works from the root (cwd on sys.path) | needs an install (editable is fine) |
| Tests can import the installed copy | not guaranteed | yes |
uv init default | no | yes: "uv prefers to define a build system and place source files in a dedicated src/<project_name>/ directory" |
| Typical for | scripts, notebooks, small apps | libraries, 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."
| Mechanism | Typed | Reads .env | Precedence | Where to use |
|---|---|---|---|---|
os.environ / os.getenv | no (strings) | no | process env | tiny scripts |
python-dotenv load_dotenv() | no | yes | README: "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) | yes | explicit merge | tests, small tools |
pydantic-settings BaseSettings | yes, validated | yes (env_file) | its docs: "environment variables will always take priority over values loaded from a dotenv file" | FastAPI services |
Laravel .env + env() in config/*.php | partly (reserved values, casts in config) | yes | Laravel 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 .envReal 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
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 / flag | Why | Cost 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.lock | layer A does not copy files, so source edits cannot bust it | slow rebuilds |
--locked | build fails if the lock is stale | image differs from CI |
--no-dev | leave dev group out | test tools in production |
--no-install-project | dependency layer only | deps reinstalled on code change |
--no-editable | project copied into site-packages | runtime stage needs the source tree |
UV_COMPILE_BYTECODE=1 | .pyc files exist at start | slower first import |
UV_LINK_MODE=copy | no hardlink warnings with cache mounts | noisy logs |
UV_PYTHON_DOWNLOADS=never | use the base image's Python | an unexpected interpreter download |
USER app | not root | root in production |
.dockerignore: .venv, .env, .git | do not copy a host environment or secrets | broken 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)| Step | Command | Fails when |
|---|---|---|
| Install | astral-sh/setup-uv | the pinned uv version is not available |
| Sync | uv sync --locked | lock is stale or a dependency cannot be resolved for the platform |
| Lint | uv run ruff check . | any selected rule fires |
| Format | uv run ruff format --check . | a file is not formatted |
| Types | uv run mypy | any type error under strict |
| Test | uv run pytest | any test fails |
| Cache trim (manual cache variant) | uv cache prune --ci | never (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 runReal 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.
| Where | What uv run changes |
|---|---|
PATH | .venv/bin first |
VIRTUAL_ENV | the project environment |
uv.lock | updated if pyproject.toml changed (unless --locked/--frozen) |
.venv | synced inexactly (--exact for exact) |
| working directory | unchanged |
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.
| Message | Command | Meaning | Fix |
|---|---|---|---|
Using CPython 3.9.6 interpreter at: /Library/Developer/CommandLineTools/... | uv lock, uv sync | which interpreter uv chose | pin with .python-version |
Resolved 44 packages in 5.67s | uv lock | resolution finished (cold cache) | none |
Creating virtual environment at: <scratch>/uvenv | uv sync | first sync created .venv (here the UV_PROJECT_ENVIRONMENT location) | none |
Prepared 15 packages in 2.51s / Installed 15 packages in 16ms | uv sync | downloaded/built, then linked from the cache | none |
Uninstalled 14 packages | uv sync --locked --no-dev | exact sync removed the dev group | expected |
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>=13 | uv lock --check | pyproject.toml changed, lock not | uv lock, commit |
same text with --locked was provided | uv sync --locked, uv run --locked | same, in CI | same |
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-123 | the name does not exist on the index | fix the name |
hint: While the active Python version is 3.9, the resolution failed for other Python versions supported by your project. | same | universal resolution checks every supported Python | narrow 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.8 | exit code 2 | allow 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 --fix | safe fixes applied | read the remaining ones |
1 file would be reformatted | ruff format --check | not formatted; exit code non-zero | run ruff format |
Success: no issues found in 5 source files | mypy | clean | none |
-e <editable install ...> in pip freeze | plain 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 reinstallReal 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
| Problem | Solution | How | Advantage | Cost / limit |
|---|---|---|---|---|
| "Works on my machine" | Lock + --locked | commit uv.lock; CI uv sync --locked | Same versions everywhere | Lock diffs in reviews |
| Wrong Python | Pin the version | .python-version, requires-python, CI matrix | Fails early | Another file |
| Global pollution | Environment per project | uv sync creates .venv | Isolation | Disk (cache hardlinks/clones reduce it) |
| Dev tools in prod | Groups + --no-dev | [dependency-groups], Docker --no-dev | Small, safer image | Must remember the flag in every command |
| Slow CI installs | Cache keyed by lock | setup-uv enable-cache, cache-dependency-glob | Seconds | Cache invalidation when the lock changes |
| Style arguments | One formatter | ruff format + CI check | No review noise | A one-time reformat commit |
| Unused imports, mutable defaults | One linter | ruff check with E F I UP B | Fast feedback | Rule choice needs thought |
| Secrets in Git | .env ignored, example committed | .gitignore, .dockerignore | No leaks | Needs scanning as a backstop |
| Many packages in one repo | Workspace | [tool.uv.workspace] | One lock | Coupled releases |
| Legacy deploy tooling wants pip | Export | uv export --no-dev > requirements.txt | Keeps old pipeline | Two 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
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| New FastAPI service | uv project, src layout, hatchling or uv_build | .python-version, uv sync --locked in CI | One tool, one lock |
| Existing Poetry project | Keep Poetry until there is a reason; try uv on a branch | Convert [tool.poetry] to [project] first | Poetry 2 reads [project] |
Existing requirements.txt workflow | uv pip sync first, then migrate to pyproject.toml | uv add -r requirements.txt | Incremental |
| One-off script | PEP 723 block + uv run | uv run --with for experiments | No project needed |
| Published library | [build-system] + ranges, extras for optional features | matrix over Python versions, ruff + mypy | Users combine your ranges |
| Data/ML notebook | Groups for heavy extras, interpreter pinned | UV_PYTHON | Large wheels are cached |
| Monorepo | Workspace | uv sync --package | One lock |
| Air-gapped deploy | uv export with hashes, vendored wheels | pip install --no-index --find-links (documented pip option, not run) | No network at install |
| Tool for everyone (formatter) | uvx ruff or uv tool install ruff | pin in lint group for CI | Consistent 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 imagesDistributed 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×
| Scale | Tooling 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)
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 52. Look inside the environment (real)
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)
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)
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)
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)
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 filesDo 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)
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 inside8. Not run here (expected)
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.txtFor 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.
// 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 / PHP | Python |
|---|---|
composer.json require | [project] dependencies |
composer.json require-dev | [dependency-groups] dev (PEP 735) |
composer.lock | uv.lock |
vendor/ | .venv/ (and site-packages inside it) |
composer install | uv sync |
composer install --no-dev | uv sync --no-dev |
composer require monolog/monolog | uv add httpx |
composer update vendor/pkg | uv 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 test | uv run pytest, Makefile, justfile |
composer global require / phar tools | uvx / uv tool install |
vendor/bin/pint | uv run ruff format . |
| PHP-CS-Fixer rule sets | Ruff rule selection (select = [...]) |
php artisan serve | uv 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.
// 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
}| Concern | Python (uv) | Go |
|---|---|---|
| Declaration | pyproject.toml | go.mod |
| Lock | uv.lock (universal, hashes) | go.sum (checksums) plus minimal version selection |
| Install location | .venv/lib/pythonX.Y/site-packages | the module cache; build output is a binary |
| Version of the language | requires-python, .python-version | the go directive in go.mod |
| Selection rule | resolver picks the highest compatible versions | "minimal version selection (MVS)" |
| Format | ruff format | gofmt |
| Lint | ruff check, mypy | go vet, golangci-lint |
| Run tools | uvx, uv tool | go run pkg@version (not run here) |
| Ship | image with .venv | a static binary in a small image |
Common misconceptions
| Belief | Reality |
|---|---|
python and python3 are the same everywhere | PEP 394: some systems provide no python; here python was "not found" |
| I must activate the venv to use it | Call .venv/bin/python or uv run; activation edits PATH only |
| A venv is a copy of Python | A directory with pyvenv.cfg pointing at the base (home = ...) and its own site-packages |
pyproject.toml pins versions | It declares ranges; the lock pins |
| Extras and dependency groups are the same | Extras 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-specific | It is universal: markers per Python version and platform (4 resolution-markers in the real lock) |
uv sync only adds packages | It is exact: it removes what the lock does not contain (14 uninstalled) |
uv venv installs pip | It does not; --seed opts in |
| Ruff only formats | ruff check is the linter; ruff format is the formatter; two commands |
ruff check --fix fixes everything safely | Unsafe fixes need --unsafe-fixes and can leave wrong code (the list[str] = None result) |
.env is production configuration | It is a development convenience; real environment variables win |
src layout is required to publish | It 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 manager | Rye is discontinued (February 2025); use uv |
Cheat sheet
| Topic | What to remember |
|---|---|
| Create a project | uv init NAME (src layout, .python-version, build backend) |
| Add / remove | uv add PKG, uv add --dev PKG, uv add --optional EXTRA PKG, uv remove PKG |
| Environment from the lock | uv sync (exact), uv sync --locked in CI |
| Run something | uv run CMD, uv run --with PKG CMD, uvx TOOL |
| Lock | uv lock, uv lock --check, uv lock --upgrade-package P |
| Production install | uv sync --locked --no-dev --no-editable |
| Docker layers | deps layer: --no-install-project; env: UV_COMPILE_BYTECODE=1, UV_LINK_MODE=copy |
| Versions | requires-python, .python-version, uv python install/pin/find |
| Specifiers | >=1,<2 range; ~=1.4.2 compatible; ; python_version < '3.11' marker |
| Extras vs groups | extras ship ([project.optional-dependencies]); groups do not ([dependency-groups]) |
| Scripts | # /// script block, uv run file.py, uv lock --script |
| Ruff | ruff check --fix . then ruff format .; CI: ruff check . and ruff format --check . |
| Rule sets | select = ["E", "F", "I", "UP", "B"], ignore = ["E501"], per-file-ignores |
| Export | uv export --no-dev --no-emit-project, with hashes for pip --require-hashes |
| Layout | src/<package>/ + tests/; editable install for development |
| Config | .env.example committed, .env ignored, real env wins |
| Debug the environment | sys.prefix vs sys.base_prefix, python -m site, python -I |
| Equivalents | Composer: composer.lock / vendor/; Go: go.sum / module cache |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| CPython | The reference Python interpreter, implemented in C |
| python.org installers | Official installers for specific Python versions |
| pyenv | Version manager that switches interpreters through shims on PATH |
uv python install | Downloads a uv-managed interpreter |
python3 vs python | The command names PEP 394 describes; python may not exist |
| PEP 394 | The "python" command on Unix-like systems |
| virtual environment | A directory with pyvenv.cfg and its own site-packages for one project |
venv | The standard-library module that creates virtual environments (python -m venv) |
| virtualenv | The third-party predecessor/superset tool |
uv venv | uv's environment creator; no pip by default |
site-packages | The directory where installed packages live |
sys.path | The list of directories Python searches for imports |
sys.prefix / sys.base_prefix | The environment root and the base installation root |
-I (isolated mode) | Ignores PYTHON* variables, the script directory and the user site |
| activate | A shell script that edits PATH and the prompt; optional |
pyproject.toml | The project's declaration file (build system, metadata, tool settings) |
| PEP 621 | Standard [project] metadata |
| project metadata | name, version, requires-python, dependencies, scripts |
dependencies | Runtime requirements in [project] |
optional-dependencies / extras | Optional 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) |
| hatchling | The Hatch project's build backend |
| setuptools | The long-standing build backend |
| tool tables | [tool.<name>] sections owned by individual tools |
| uv | A single binary for interpreters, environments, locking, running and tools |
uv init / add / remove | Create a project / add or drop a dependency |
uv sync / uv lock / uv run | Install the lock / resolve / run in the environment |
uv python | Interpreter management subcommands |
uvx / uv tool | Run or install tools in isolated environments |
uv pip | pip-compatible commands inside uv |
| uv workspace | Several packages sharing one lock ([tool.uv.workspace]) |
| inline script metadata (PEP 723) | A # /// script comment block with dependencies for a single file |
| uv cache | Global store of downloaded and built packages, linked into environments |
| pip | The standard installer |
pip-tools / pip-compile | Pins requirements.in into a platform-specific requirements.txt |
| Poetry / PDM / Rye / Hatch | Other project managers; Rye is discontinued |
lockfile / uv.lock | Exact resolved versions, hashes and markers, committed to Git |
requirements.txt / uv export | pip's file format and the uv command that writes it from the lock |
| reproducible installs | The same versions and files on every machine |
| hashes | SHA-256 digests; pip --require-hashes refuses mismatches |
| platform markers / environment markers (PEP 508) | Conditions such as python_version < '3.11' |
| PEP 440 | Version identification and specifiers |
| version specifiers | ==, >=, <, ~=, !=, .* |
| pin vs range | Exact version vs accepted interval |
| caret vs tilde | ^ and ~ in Composer and Poetry; PEP 440 only has ~= |
| Ruff | Linter and formatter in one binary |
ruff check / ruff format | Lint (with --fix) / format (with --check) |
| rule selection | select, ignore and prefixes such as E, F, I, UP, B |
| isort rules / pyupgrade rules | Rule families I and UP |
line-length | Width shared by the formatter and E501 |
| per-file-ignores | Rules disabled for matching paths |
| pre-commit | Git hook framework that runs Ruff before commits |
| Black compatibility | Ruff's formatter emits near-identical Black output |
| mypy / pyright | Static type checkers |
| pytest as a tool | The test runner, in the dev group |
| task runner | uv run, Makefile, justfile, taskipy |
--no-dev | Skip the default dev group when syncing |
UV_COMPILE_BYTECODE | Compile .pyc files at install time |
| multi-stage build | A builder image whose .venv is copied into a smaller runtime image |
astral-sh/setup-uv | The GitHub Action that installs uv and caches it |
src layout / flat layout | Package under src/ vs in the repository root |
.env / python-dotenv / pydantic-settings | Local 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-Fixer | PHP code style fixers |
go.mod / go.sum | Go module requirements and checksums |
gofmt / go vet | Go'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.