01B.1 Project Setup with uv: Environments, Dependencies and Tooling
The first thing every later lesson in this module assumes is a working Python project: a folder where dependencies are declared, installed reproducibly, and run with one command. This lesson builds that foundation properly. You will learn what a virtual environment really is, what pyproject.toml and a lockfile do, how to install and drive uv — the tool this whole path uses — and how to set up the aitoolkit project that lessons 01B.2 through 01B.10 build on. Along the way you will meet the rest of the Python packaging landscape (pip, pipx, Poetry, PDM, conda), version specifiers and pinning, the src/ layout, and the everyday tooling (ruff, type checkers, pre-commit, pytest, notebooks, Docker and CI) that turns a folder of scripts into a project a team can ship.
What you'll learn
- Why "works on my machine" happens, and what reproducible project setup actually means
- What a virtual environment is, what
pyproject.tomlis (PEP 621), and why you commit a lockfile - How to install
uv, create projects (uv initand its--bare,--app,--lib,--packageand--scriptmodes), and manage them withuv add,uv remove,uv sync,uv lock,uv run,uv treeanduv export - How
uvmanages Python versions (uv python install/list/find/pin,.python-version), command-line tools (uv tool install,uvx), single-file scripts (PEP 723 inline metadata), workspaces, caches, indexes and theuv pipcompatibility layer - How to read and write version specifiers (
==,>=,~=,!=), why libraries pin loosely and applications pin tightly, and how to upgrade and audit dependencies safely - The standard project layout (
src/vs flat,tests/,scripts/,data/,.env,.gitignore,README.md,Makefile/justfile), and the completeaitoolkitskeleton - The developer toolchain: ruff, type checkers, pre-commit hooks, editor integration, pytest, EditorConfig, notebooks, and previews of Docker and CI
- A troubleshooting table for the errors every Python learner hits, and a failure gallery
What you don't need
- Any prior experience with packaging tools. If you have only ever run
pip installandpython script.py, this lesson starts exactly there. - Any API keys. This lesson needs no provider access and makes no network calls beyond installing packages from PyPI.
- Module 01A's content re-taught: this lesson assumes you can write functions, classes and imports (Module 01A covers those).
Setup
You need uv, the package and project manager this path standardises on. Install it from the official installation page — for example on macOS and Linux:
curl -LsSf https://astral.sh/uv/install.sh | shOn Windows, open PowerShell and run uv's documented installer, then open a new terminal so uv is on your PATH:
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"Then verify, and let uv fetch the Python version this path targets (3.13):
uv --version # e.g. uv 0.13.7 — check https://pypi.org/project/uv/ for the current release
uv python install 3.13 # downloads a managed CPython if you don't have one; safe to re-run
uv python list # every interpreter uv can see, managed and systemYou do not need to install Python yourself: uv downloads and manages CPython builds. You also do not need git for most of this lesson, but uv init creates a git repository for you, so it helps to have git installed (00.1 covers that if you haven't).
Every command in this lesson is shown for macOS/Linux (bash) and, where it differs, for Windows PowerShell. uv's own docs note that uv works the same on all three; the shell differences that matter are covered as they come up.
What you must be able to do after this lesson#
- Explain why works on my machine happens and what reproducible setup means
- Create a project with uv init and add dependencies with uv add
- Commit pyproject.toml and the lockfile and rebuild the environment with uv sync
- Run code and tools inside the project environment with uv run
- Read and write version specifiers such as == and >= and choose loose or tight pins
- Lay out a project with src, tests and a gitignore
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
"Clone the repo and run uv sync — don't ask me how." |
4.3 Managing dependencies |
| "The bug only happens on my machine." | Part 1: Why this matters |
| "Pin it exactly — the SDKs break every few weeks." | Part 6: Versions and pinning |
"Commit uv.lock, never edit it." |
2.5 The lockfile |
"Why is there a .venv folder and why isn't it in git?" |
2.3 Virtual environments |
"uv run just works — do we still need to activate anything?" |
4.4 Running commands |
"That script has # /// script at the top — what is it?" |
4.6 Single-file scripts: PEP 723 |
"My colleague's pyproject.toml has [dependency-groups] — what's dev?" |
2.4 pyproject.toml and PEP 621 |
"uv add --dev pytest vs uv add pytest — which one?" |
4.3 Managing dependencies |
"We need ruff and a type checker before this merges." |
Part 8: Developer tooling |
"The Dockerfile starts COPY --from=ghcr.io/astral-sh/uv — why?" |
Part 10: Docker and CI previews |
Part 1: Why project setup is the first engineering skill#
1.1 The problems this lesson solves#
Ask ten engineers how they got their first Python project running and nine will describe some version of this: install Python, pip install a list of packages copied from a tutorial, write main.py, run it, and it works. Then they push the code, a teammate clones it, and it doesn't work. Or it works today and breaks next month when a dependency publishes a new version.
The failure has a name — "works on my machine" — and it has three root causes:
- Dependency conflicts. Project A needs
httpx0.28, project B needshttpx0.26. If both install into the same Python, the second install silently replaces the first, and one of the projects breaks. This is why you never install project packages into your system Python. - Version drift.
pip install openaiwith no version installs whatever is newest today. Six weeks later the same command installs something different, and code that worked may not. AI SDKs are the worst offenders: theopenai,anthropicandgoogle-genaipackages in this path release new versions every few days, and major versions occasionally break the API (lesson 03.1, 9.4 covers SDK versioning). This path's ownuv addcommands name packages without version numbers, so the protection against drift is the committeduv.lock, which records the exact versions you were given (4.3, Part 6). - Undeclared state. The tutorial's
pip installlist lives in a README, a chat message, or someone's memory. Nobody wrote down exactly which versions the code was tested against, including the versions of dependencies' dependencies.
A reproducible project fixes all three: dependencies are declared in a file, resolved to exact versions once, locked in a file you commit, and installed into an isolated environment with one command. Anyone — a teammate, CI, a Docker build, future you — gets the same environment.
1.2 What "the environment" actually means#
Before the tools, the concepts — because every tool in this lesson is just a different way of managing the same three things:
- The interpreter: the
pythonprogram itself, with its version (3.13.14, say) and its standard library (the batteries included:json,http,pathlib,asyncio...). - Site-packages: the folder where third-party packages (
httpx,pydantic,pytest...) get installed, next to the interpreter. - The environment: interpreter + site-packages + a few markers that say "this is where packages live". One Python install can hold many environments' worth of confusion if you install everything globally — which is exactly what virtual environments prevent.
The next part takes each apart.
Part 2: The moving parts of a Python project#
2.1 The interpreter and the standard library#
python3 --version tells you which interpreter your shell finds first on the PATH. That interpreter ships with the standard library — modules like json, urllib, sqlite3, tomllib — and nothing else. Anything you import that isn't standard library must come from site-packages.
The trap: the interpreter your shell finds is often not the one a project needs. Your laptop might have Python 3.9 from the OS, 3.14 from Homebrew, and 3.13 managed by uv — and different projects need different versions. Tools solve this by pinning a version per project (4.5).
2.2 Site-packages: where "installed" lives#
When you run pip install requests, pip downloads a wheel (a .whl file — a zip with the package's code plus metadata) from PyPI and unpacks it into the environment's site-packages directory, recording it in that environment's metadata. "Installed" therefore always means installed into a specific environment — there is no global list of "packages Python has".
Two consequences:
- The same package name can exist at different versions in different environments simultaneously. That's a feature, not a bug.
- Deleting
.venv/and recreating it gives you a clean slate — which is why.venvis never committed to git (it can always be rebuilt).
2.3 Virtual environments#
A virtual environment (venv) is a folder — conventionally .venv/ inside the project — containing a private Python environment: its own python executable, its own site-packages, its own pip. Packages installed there are invisible to every other environment on the machine.
The classic way to make one is python3 -m venv .venv, then "activate" it so python and pip resolve to the venv's copies. You can see the mechanism directly — sys.prefix is the environment's root, sys.base_prefix is the real interpreter's:
# venv_probe.py — run inside and outside a venv to see the difference
import sys
print("prefix == base_prefix ->", sys.prefix == sys.base_prefix)
print("prefix ends with .venv ->", sys.prefix.endswith(".venv"))prefix == base_prefix -> False
prefix ends with .venv -> Trueprefix == base_prefix -> True
prefix ends with .venv -> FalseInside the venv, sys.prefix points at .venv while sys.base_prefix still points at the real interpreter — the venv is a layer on top of the base Python, sharing its standard library but not its site-packages. A fresh venv contains only pip itself: no setuptools, no packages. That isolation is the whole point.
Activation is the old ritual: source .venv/bin/activate on macOS/Linux (.venv\Scripts\Activate.ps1 in PowerShell on Windows) makes python/pip in that shell point into .venv. It is easy to forget, which is why uv run exists: uv creates and syncs .venv automatically and runs your command inside it, so activation becomes optional (4.4).
2.4 pyproject.toml and PEP 621#
pyproject.toml is the project's manifest: one TOML file (a minimal key = "value" config format) that says what the project is, what Python it needs, what it depends on, and how tools should behave. PEP 621 — a Python Enhancement Proposal, the standards-track document — standardised the [project] table so every tool (pip, uv, Poetry, PDM, build backends) reads the same metadata.
The parts you will see constantly:
# pyproject.toml — the [project] table (PEP 621) and a tool section
[project]
name = "aitoolkit" # distribution name (what `uv add` writes back to)
version = "0.1.0" # the project's own version (semantic versioning: MAJOR.MINOR.PATCH)
description = "Shared toolkit for the AI engineering path"
requires-python = ">=3.13" # the minimum Python; uv picks an interpreter that satisfies it
dependencies = [ # runtime dependencies, PEP 508 strings
"httpx",
"pydantic",
]
[dependency-groups] # PEP 735: named sets installed on demand
dev = ["pytest", "ruff"]
[tool.ruff] # tool configuration lives under [tool.*]
line-length = 100Field by field:
| Field | What it does |
|---|---|
name |
The distribution name. Must be unique on PyPI if you ever publish; for private projects any slug works (aitoolkit). |
version |
Your project's version. Tools like uv version read it; bump it when you release. |
requires-python |
A version specifier for the interpreter, not a package. ">=3.13" means "3.13 or newer". This is what makes uv init --python 3.13 write >=3.13 — and what makes uv python pin 3.12 fail in a >=3.13 project (the real error appears in 4.5). |
dependencies |
Runtime requirements as PEP 508 strings: name, name==1.2.3, name>=1.0,<2, name[extra], name @ https://.... Specifier syntax is covered in Part 6. |
[dependency-groups] |
PEP 735 dependency groups: named lists like dev, docs, lint. The dev group is installed by default by uv sync; others install on demand (uv sync --group docs). uv also has [project.optional-dependencies] ("extras") for published packages — the difference matters when you publish, and is covered in 7.3. |
[tool.*] |
Configuration for tools that read pyproject.toml: [tool.ruff], [tool.pytest.ini_options], [tool.uv], [tool.ty], and so on. Keeping tool config next to project metadata is why pyproject.toml became the hub of the Python ecosystem. |
You can read all of this with the standard library — tomllib parses TOML since Python 3.11:
# read_pyproject.py — what a tool "sees" when it opens pyproject.toml
import tomllib
with open("pyproject.toml", "rb") as f:
data = tomllib.load(f)
print("name:", data["project"]["name"])
print("requires-python:", data["project"]["requires-python"])
print("deps:", data["project"]["dependencies"])
print("dev group:", data["dependency-groups"]["dev"])
print("ruff line-length:", data["tool"]["ruff"]["line-length"])name: aitoolkit
requires-python: >=3.13
deps: ['httpx', 'pydantic']
dev group: ['pytest', 'ruff']
ruff line-length: 1002.5 The lockfile#
pyproject.toml says what you want (httpx>=0.28); a lockfile records what you got: the exact version of every package and every transitive dependency (a dependency of a dependency — httpx itself pulls in certifi, httpcore and friends), plus the hashes of the files downloaded and the markers that decide which packages apply on which platform. Producing that list is the resolver's job: the algorithm that reads every specifier and picks one compatible version per package.
uv's lockfile is uv.lock, a human-readable TOML file that uv manages for you — you never edit it by hand. uv's own documentation is explicit: it "should be checked into version control". Committing it is what makes uv sync on a teammate's machine, in CI, and in Docker install exactly the versions you tested, including on platforms you never ran on (the lock records per-platform resolution).
flowchart LR
subgraph declare ["You declare"]
PP["pyproject.toml<br/>(PEP 621 metadata + dependency specifiers)"]
DG["[dependency-groups]<br/>dev tools"]
end
subgraph resolve ["uv resolves"]
RES["Resolver picks one<br/>compatible version<br/>for every package"]
end
subgraph lock ["Committed to git"]
LK["uv.lock<br/>exact versions + hashes +<br/>markers for every platform"]
end
subgraph env ["Installed on each machine"]
VENV[".venv/<br/>the project's own<br/>Python environment"]
CODE["your code<br/>import httpx, pydantic..."]
end
PP --> RES
DG --> RES
RES --> LK
LK -->|"uv sync / uv run"| VENV
VENV --> CODEA trimmed uv.lock looks like this (from a real uv lock run on a project with no third-party deps — the virtual source means "the project itself is not installed as a package", which happens with --bare/--no-package projects):
# uv.lock — managed by uv; do not edit by hand
version = 1
revision = 3
requires-python = ">=3.13"
[[package]]
name = "demo"
version = "0.1.0"
source = { virtual = "." }With real dependencies, each [[package]] entry also carries version, source (registry, git, path...), dependencies, sdist/wheels entries (the source distribution and prebuilt wheel forms, each with url and hash), and resolution-markers for platform-specific picks. You will rarely need to read it deeply — uv tree gives you the readable view (4.3) — but knowing it's there explains every "why did CI install a different version" mystery: the answer is almost always "someone didn't commit the lockfile" or "someone edited it".
Part 3: The classic tooling, and why it hurt#
Reference
Before uv, setting up a Python project was a chain of separate tools, each with its own failure modes. Understanding them explains both why uv exists and why you will still meet them.
3.1 pip and venv#
The standard-library path is:
python3 -m venv .venv # create the environment
source .venv/bin/activate # macOS/Linux; PowerShell: .venv\Scripts\Activate.ps1
pip install httpx pydantic
pip freeze > requirements.txt # record what you installedThis works, and millions of projects use it. Its limits are exactly the problems from Part 1:
pip installresolves at install time, one package at a time, and can produce different results on different days (a dependency released yesterday can change today's resolution).requirements.txtfrompip freezerecords versions but not the resolution rules — re-installing it is deterministic, but updating it is guesswork.pipinstalls into whatever environment is active; forget to activate and you pollute your system Python (and then hitexternally-managed-environmenterrors on distro Pythons, covered in 11.1).pipis slow: it re-downloads and re-builds constantly. uv's resolver and cache are dramatically faster — Astral's benchmarks show order-of-magnitude improvements on cold and warm installs, and uv's own docs make the same claim (uv benchmarks).
3.2 pipx and uv tool: applications, not libraries#
pipx solves a different problem: installing command-line applications (black, httpie, awscli, ruff as a standalone tool) into isolated environments of their own, exposing their executables on your PATH. pipx install ruff gives you a ruff command without touching any project's environment.
uv covers the same ground with uv tool install and uvx (4.7). pipx remains the standard answer on machines without uv; Part 5 compares them properly.
3.3 externally-managed-environment: the error that taught a generation#
Linux distributions (Debian, Ubuntu, Fedora...) ship a Python marked externally managed: pip install into it is refused with:
error: externally-managed-environment
× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
python3-xyz, where xyz is the package you are trying to
install.The reason is sound — distro Pythons are shared infrastructure, and pip installs would break the package manager's bookkeeping. The fix is always the same: use a virtual environment (or uv, which creates one automatically). The full entry is in 11.1.
Part 4: uv in depth#
uv is a single Rust binary that does everything Part 3 needed three tools for: it installs Python interpreters, creates and manages virtual environments, resolves and locks dependencies, installs them, runs commands inside the project environment, manages command-line tools, and even runs dependency-free scripts. It is written by Astral (the makers of Ruff) and is released under MIT/Apache-2.0.
The version used throughout this lesson's real runs was uv 0.12.1; the current release is 0.13.7 (as of November 2026, https://pypi.org/project/uv/). Everything shown here exists in both — check uv --version and the command reference if a flag ever surprises you.
4.1 Installing uv and Python#
Installation is one command per platform, from the official page:
# macOS and Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# Windows PowerShell
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"Verify:
uv --versionuv 0.13.7 (Homebrew 2026-11-03 aarch64-apple-darwin)Python versions. You do not need to install Python at all. uv python install 3.13 downloads a standalone CPython build into uv's own directory (~/.local/share/uv/python on macOS/Linux), independent of Homebrew, apt or the Microsoft Store. Useful subcommands:
uv python list # interpreters uv can see (managed + system + requested)
uv python find 3.13 # path to the interpreter uv would use
uv python pin 3.13 # write ./.python-version (inside a project)
uv python install 3.13 # download a managed build if missing
uv python install --default 3.13 # also install unversioned python/python3 executables
uv python update-shell # put ~/.local/bin (where those executables live) on your PATH
uv python upgrade # update managed builds to latest patch releases
uv python uninstall 3.10 # remove a managed buildPer the Python versions docs, --default is experimental and installs unversioned python/python3 executables into uv's executable directory (~/.local/bin on Unix); uv python update-shell is what edits your shell profile to put that directory on PATH. You will rarely need either — uv run finds managed Pythons itself — but it's good to know they exist.
The managed builds are ordinary CPython — same python3.13 binary you'd get elsewhere, just downloaded by uv and kept out of your system package manager. uv only downloads a Python when a project or command needs a version you don't have; uv init --python 3.13 triggers that automatically. To upgrade uv itself later, run uv self update (or re-run the installer).
4.2 uv init: creating a project#
uv init aitoolkit --package --python 3.13
cd aitoolkituv init scaffolds a project. Its flags select the shape:
| Flag | Creates | Use it when |
|---|---|---|
| (default) | src-layout project, [project.scripts] entry point, uv_build backend, .python-version, README, git repo |
Most projects (same as --package in current uv) |
--package |
Same as default: an installable package | Your code will be imported as aitoolkit — this path's choice |
--app |
Application template (in current uv, same layout as --package) |
An app you run, not a library others import |
--lib |
Library template: src layout plus py.typed, no console script |
A package meant to be imported and type-checked by others |
--bare |
Only pyproject.toml — no src tree, no scripts, no build-system, no .python-version, no git |
Scripts-and-dependencies folders like Module 03's llm-apis project (03.1, 4.2) |
--script |
A single PEP 723 script file (uv init tool.py --script) |
One-off scripts (4.6) |
--no-package |
Project without a build backend — nothing gets installed, code stays as loose files | Quick tools that never need import aitoolkit from an installed package |
Other useful flags (verified against uv init --help on 0.12.1): --name, --description/--no-description, --vcs git|none (default: git init outside an existing repo), --author-from auto|git|none (the authors field is filled from your git config — you can suppress it), --no-pin-python (skip .python-version), --no-readme, --no-workspace (don't join a parent workspace), --build-backend uv|hatch|flit|pdm|poetry|setuptools|maturin|scikit.
A real run, condensed (uv 0.12.1; uv init demo2 --python 3.13):
Initialized project `demo2` at `/private/tmp/uvdemo.DKCy1T/demo2`created pyproject.toml, .python-version (containing 3.13), .gitignore, README.md, src/demo2/__init__.py, and a .git repository. The generated pyproject.toml (authors line sanitised — the real run filled it from the machine's git config):
[project]
name = "demo2"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
authors = [
{ name = "Your Name", email = "you@example.com" }
]
requires-python = ">=3.13"
dependencies = []
[project.scripts]
demo2 = "demo2:main"
[build-system]
requires = ["uv_build>=0.12.1,<0.13.0"]
build-backend = "uv_build"Notes that matter:
requires-python = ">=3.13"came from--python 3.13. Omit the flag and uv infers the minimum from the first interpreter it finds — which may be 3.9 or 3.10 and will makeuv addfail later with a wall of "No solution found" text (11.1 shows that error). Always pass--python 3.13for this path.uv_build>=0.12.1,<0.13.0is the build backend pin uv writes for its own version — with uv 0.13.x it writes a0.13.xbound. Don't hand-edit it;uvmanages it..python-versionpins the minor version uv reaches for first;requires-pythonis the real constraint. Both are committed.--barecreates onlypyproject.toml— verified: no.python-version, no.gitignore, no git repo. Module 03's setup relies on this and adds.env/.gitignoreby hand (03.1, 4.2).
flowchart TD
Q{"What are you building?"} --> Q1{"A single file<br/>or a throwaway script?"}
Q1 -- "yes" --> S["uv run script.py<br/>with a PEP 723 header"]
Q1 -- "no" --> Q2{"Will you ship it<br/>as a package others install?"}
Q2 -- "yes" --> LIB["uv init name --lib"]
Q2 -- "no" --> Q3{"Does it need a<br/>command-line entry point?"}
Q3 -- "yes" --> APP["uv init name --app<br/>(or --package)"]
Q3 -- "no, just run it" --> BARE["uv init name --bare<br/>or --no-package"]4.3 Managing dependencies#
uv add httpx # add a runtime dependency (writes a lower bound, e.g. httpx>=0.28.1)
uv add 'pydantic>=2.14,<3' # add with a specifier
uv add --dev pytest # add to the default `dev` dependency group
uv add --group docs mkdocs # add to a named group
uv add -r requirements.txt # migrate an old requirements file
uv remove httpx # remove a dependency
uv lock # re-resolve and rewrite uv.lock only
uv sync # make .venv match the lockfile exactly
uv sync --locked # sync, but fail if uv.lock is stale
uv sync --frozen # sync from the lockfile without checking freshness
uv tree # show the resolved dependency tree
uv export --format requirements.txt # write a requirements.txt from the lock
uv export --format pylock.toml # PEP 751 format (also cyclonedx1.5 for SBOMs)
uv lock --upgrade-package httpx # upgrade one package, keep the rest pinned
uv lock --upgrade # upgrade everything within specifiersWhat each does, precisely:
uv add <pkg>is the command you will use 95% of the time. It appends a PEP 508 requirement topyproject.toml(respecting--bounds:lower— the default — writes just a lower bound likehttpx>=0.28.1;majorallows the same major version (>=1.2.3,<2.0.0-style, like semver's caret);minorallows the same minor (>=1.2.3,<1.3.0-style, like semver's tilde);exactpins==x.y.z— e.g.uv add httpx --bounds exact), re-resolves, rewritesuv.lock, and syncs.venv. One command keeps all four artefacts consistent — that is the whole point of a project manager.uv remove <pkg>does the reverse across the same three files — but it targetsproject.dependenciesby default. For a package that lives in a dependency group or an extra, pass the matching selector:--dev,--group <name>or--optional <extra>(e.g.uv remove --group dev pytest). Plainuv remove pyteston a dev-only package fails with a hint naming the right flag — the symmetric trap touv add --dev.uv lockre-runs the resolver and rewritesuv.lockwithout touching.venv.uv lock --checkverifies freshness without writing;uv lock --dry-runshows what would change.uv syncmakes.venvmatchuv.lockexactly: installs missing packages, updates changed ones, and removes extraneous ones (packages in.venvthat aren't in the lock). By default it includes thedevdependency group;--no-dev,--only-dev,--group,--no-group,--all-groups,--only-group,--inexacttune that.uv treeprints the resolved tree — the readable answer to "why iscertifiinstalled?" (becausehttpxneeds it).uv exportconverts the lockfile to other formats for tools that only speakrequirements.txt(older Dockerfiles,pip install -r, some deploy targets) or SBOMs (cyclonedx1.5) or PEP 751 (pylock.toml). Export is a compatibility shim — your source of truth staysuv.lock.uv lock --upgrade-package <pkg>is the deliberate-upgrade path: it re-resolves allowing only that package (and what it forces) to move, keeping everything else pinned. This is how you take a security fix or a needed feature without absorbing every other release in the ecosystem. Run your tests before committing the result.
A real uv add-equivalent lifecycle, condensed from actual runs (uv 0.12.1 — timings and temp paths vary per machine, so this transcript is Example output (illustrative — your exact output will differ):; package installs themselves were not run — they need the index):
$ uv init demo --bare --python 3.13
Initialized project `demo` at `/private/tmp/uvdemo.DKCy1T/demo`
$ cd demo && uv lock
Using CPython 3.13.14
Resolved 1 package in 16ms
$ uv sync
Using CPython 3.13.14
Creating virtual environment at: .venv
Resolved 1 package in 3ms
Checked in 0.47ms
$ uv run python -c "import sys; print(sys.prefix.endswith('.venv'))"
TrueAnd the --locked guard catching a stale lockfile — real output shape from uv 0.12.1 (Example output (illustrative — your exact output will differ): — the package count and timing vary; the error text is verbatim):
$ uv sync --locked
Resolved 6 packages in 241ms
error: The lockfile at `uv.lock` needs to be updated, but `--locked` was provided.
hint: To update the lockfile, run `uv lock`.4.4 Running commands#
uv run python app.py # sync env, then run inside it
uv run pytest # same, for any command on PATH in the env
uv run --with httpx python scratch.py # add throwaway deps for one run ([Part 9](#part-9-notebooks-and-scratch-work))
uv run --no-project script.py # skip the surrounding project (script-env rules: [4.6](#46-single-file-scripts-pep-723-inline-metadata))
uv run --locked app.py # assert the lockfile is fresh (CI habit)
uv run --frozen app.py # don't even check; use the lock as-isBefore every uv run, uv verifies that uv.lock still matches pyproject.toml and that .venv matches the lock — then syncs only if something drifted. This is why uv run is the answer to "do I need to activate?": no. Activation scripts still work (source .venv/bin/activate), and uv run --active prefers an already-active venv, but the intended workflow is uv run everywhere, which also means CI and Docker never need activation either.
A sequence diagram of the everyday loop:
sequenceDiagram
participant Dev as "You (terminal)"
participant UV as "uv"
participant PP as "pyproject.toml"
participant LK as "uv.lock"
participant VENV as ".venv"
participant PY as "python"
Dev->>UV: uv add httpx
UV->>PP: append "httpx>=0.28.1" to dependencies
UV->>LK: resolve + write exact versions
UV->>VENV: install the new environment
Dev->>UV: uv run python app.py
UV->>PP: check dependencies unchanged?
UV->>LK: check lockfile fresh?
UV->>VENV: sync if needed
UV->>PY: run app.py inside .venv
PY-->>Dev: output4.5 Python versions: uv python and .python-version#
Two files control which interpreter a project uses, and they answer different questions:
| File / command | Question it answers |
|---|---|
requires-python in pyproject.toml |
"What Python versions may this project use?" — a constraint like >=3.13, checked by the resolver for every dependency too. |
.python-version |
"Which interpreter should uv pick first?" — a pin like 3.13 or 3.13.14. Written by uv python pin or uv init --python. |
The workflow: uv init --python 3.13 writes both (requires-python = ">=3.13" and .python-version containing 3.13). Later, uv python pin 3.12 inside the project fails — verified real output:
$ uv python pin 3.12
error: The requested Python version `3.12` is incompatible with the project `requires-python` value of `>=3.13`.— because the pin must satisfy the constraint. uv python pin 3.13 then writes .python-version containing 3.13. If you genuinely need to support 3.12, edit requires-python to ">=3.12" first, then pin.
uv python find 3.13 shows which interpreter uv would select; uv python list enumerates everything it can see — managed builds (downloaded by uv into ~/.local/share/uv/python), system interpreters on PATH, and interpreters requested by .python-version files. Downloads are automatic but only happen when needed; UV_PYTHON_DOWNLOADS=never or --no-python-downloads disables that if you want failures instead of surprises (useful in locked-down CI).
4.6 Single-file scripts: PEP 723 inline metadata#
Not everything deserves a project. A single-file script — a data-cleaning one-off, a migration helper, a notebook replacement — can declare its own dependencies inside the file using PEP 723 inline metadata, a TOML comment block at the top:
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "httpx",
# ]
# ///
"""fetch_titles.py — grab page titles; deps live in this file, not a project."""
import httpx
for url in ["https://example.com"]:
print(url, "->", httpx.get(url, timeout=10).status_code)Run it with uv run fetch_titles.py: uv reads the block, builds (or reuses a cached) ephemeral environment containing exactly those deps, runs the script, and discards nothing you need to manage. No pyproject.toml, no .venv, no activation. uv add --script fetch_titles.py rich edits the block for you; uv lock --script fetch_titles.py writes a fetch_titles.py.lock beside it for reproducibility; uv run --script forces script mode.
Rules that bite:
dependenciesmust be present even when empty — a script block without it is invalid (the docs say so explicitly).- Inside a project directory,
uv run script.pystill applies script metadata — the project's dependencies are ignored entirely (uv's docs are explicit that--no-projectisn't even required for that). Script metadata is only read when the.pyfile itself is the command uv runs, souv run python script.pyexecutes in the project environment instead, whileuv run --no-project python script.pygives a bare interpreter with neither the project's nor the script's packages (Exercise 6 shows both). - The shebang
#!/usr/bin/env -S uv run --scriptmakes the file directly executable on macOS/Linux (chmod +x, then./script.py) — the docs' recommended trick for PATH-installed scripts.
Real run (uv 0.12.1, empty deps so it worked fully offline):
# hello.py
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
import sys
print("hello from", sys.version.split()[0])$ uv run hello.py
hello from 3.13.14(Example output (illustrative — your exact output will differ): the patch version is whatever interpreter uv selects.)
4.7 Tools: uv tool install and uvx#
CLI applications you want on your PATH — ruff, pytest-adjacent helpers, mkdocs, awscli-style tools — install the uv tool way:
uv tool install ruff # installs ruff into an isolated env, exposes `ruff` on PATH
uvx ruff --version # uv tool run: fetch (or reuse) and run, no permanent install
uvx --from 'ruff==0.17.4' ruff check . # pin the tool version per invocation
uv tool list # what's installed
uv tool upgrade ruff # upgrade one tool
uv tool uninstall ruffuvx (short for uv tool run) is the "run it once" version: uvx ruff check . downloads ruff into a cached tool environment, runs it, and leaves it cached for next time. This is the modern replacement for pipx run and for npx-style one-shots — invaluable for trying a tool without committing to it. Tools live in uv's own directory, completely separate from any project's .venv, so a project's pinned ruff (a dev dependency) and your global ruff tool never collide.
4.8 Workspaces: multi-package repos#
When one repository holds several related packages — say aitoolkit plus a aitoolkit-cli and shared aitoolkit-core — a workspace lets them share one lockfile and one .venv while keeping separate pyproject.toml files. The root pyproject.toml declares members:
# pyproject.toml (workspace root)
[tool.uv.workspace]
members = ["packages/*"]uv sync then installs every member and resolves them together; uv run --package aitoolkit-cli ... picks which member's environment view to use; uv lock produces one uv.lock for the whole workspace. Path dependencies between members are declared with [tool.uv.sources] (aitoolkit-core = { workspace = true }). You won't need workspaces for the module projects — they exist for monorepos — but knowing the word prevents confusion when you meet it in a real codebase. Full docs: uv workspaces.
4.9 The uv cache, indexes and private registries#
uv keeps a global cache (~/.cache/uv on macOS and Linux — uv follows XDG conventions on both, so $XDG_CACHE_HOME/uv wins if set — and %LOCALAPPDATA%\uv\cache on Windows) of downloaded wheels, built source distributions and resolved metadata. This is why repeat uv syncs are near-instant and why uv feels faster than pip even on first installs of pure-Python wheels — it hardlinks cached wheels into .venv instead of copying. Cache controls: uv cache clean, uv cache prune (drop stale entries and cached script environments), uv cache size (see what it's using), uv cache dir, --no-cache, UV_CACHE_DIR. uv also caches Python downloads, so uv python install 3.13 on a second machine is fast.
Indexes. By default uv resolves from PyPI. You can add indexes per-project or globally:
# pyproject.toml
[[tool.uv.index]]
name = "internal"
url = "https://pkgs.example.com/simple"uv add --index internal internal-package # resolve this package from that index
uv sync --default-index https://pkgs.example.com/simple # or point everything elsewhere(--index-url still works but is the deprecated alias for --default-index — the same deprecation applies to uv add/uv remove/uv lock and friends.)
Private indexes need credentials — uv reads them from UV_INDEX_URL/netrc/keyring or uv auth login (authentication docs). For this path, PyPI is enough; the awareness matters when your employer hosts an internal mirror or you consume a private package. Always prefer [[tool.uv.index]] in pyproject.toml over environment hacks so the index choice is committed and reproducible.
One ecosystem-specific wrinkle worth knowing: the PyTorch packages publish to their own indexes per backend (CPU, CUDA cu126, ROCm...). uv has a torch-backend setting ([tool.uv] torch-backend = "cpu" or "cu126"/"auto" to detect your CUDA drivers) that redirects the PyTorch ecosystem to the right index — it's in preview and currently respected by uv pip commands (settings reference, PyTorch guide). You won't need it for LLM API work, but it's the answer when a torch install picks the wrong (huge) wheel.
4.10 Locking modes: --locked, --frozen, --check#
Three flags guard the lockfile contract, and CI uses all of them:
| Flag | Behaviour | Use it when |
|---|---|---|
uv lock --check |
Fail if uv.lock doesn't match pyproject.toml; write nothing |
A CI step that verifies the lock is fresh |
uv sync --locked |
Sync .venv, but fail if the lock would need changes |
CI installs: proves the committed lock is what runs |
uv sync --frozen |
Sync from uv.lock without checking it matches pyproject.toml |
Deploys/builds that must use the lock exactly as committed (e.g. a release artefact) |
uv run --locked / --frozen |
Same guarantees per-invocation | Local discipline or CI scripts |
The --locked failure you saw in 4.3 is the guard working: it resolved the new requirement, saw the lock couldn't satisfy it unchanged, and refused. --frozen would instead install the old lock silently — correct for "reproduce this exact build", wrong for "check my work".
4.11 uv pip: the compatibility layer#
Scripts, Dockerfiles and tutorials written for pip keep working because uv pip mirrors pip's interface against any environment:
uv pip install --python .venv/bin/python requests # or VIRTUAL_ENV=.venv
uv pip list --python .venv/bin/python
uv pip freeze --python .venv/bin/python
uv pip compile requirements.in -o requirements.txt # like pip-tools compile
uv pip sync requirements.txt # like pip install -r, but exact
uv pip tree --python .venv/bin/python
uv pip check --python .venv/bin/python # verify dependency compatibilityuv pip targets whatever --python/VIRTUAL_ENV/active venv you point at — including environments uv didn't create. Use it for migration and for tools that emit requirements.txt; for day-to-day project work, uv add/uv sync/uv run are the better interface because they keep pyproject.toml and uv.lock in the loop. Docs: the pip interface.
Part 5: The packaging landscape: pip, pipx, Poetry, PDM, conda, uv#
Reference
Python's packaging world grew organically, so "the Python package manager" is really six different tools answering six different questions. Versions below are current as of November 2026 (PyPI/project pages linked).
| Tool | What it manages | Lockfile? | Python versions? | Best for | Watch out for |
|---|---|---|---|---|---|
| pip (bundled) | Packages into whatever env is active | No (pip freeze is a snapshot, not a resolver lock) |
No | Inside venvs, minimal images, uv pip fallback |
No resolution reproducibility; slow; easy to hit the wrong env |
| venv (stdlib) | Creates the isolated environment only | No | No | The primitive everything else builds on | Manual activation; no dependency logic at all |
| pipx (1.18.x) | CLI applications in isolated envs, on PATH |
No | No | ruff, httpie, dev tools |
Not for project deps; no lockfile |
| Poetry (2.5.x) | Projects: deps, venvs, publishing to PyPI | poetry.lock |
Can install Python | Mature all-in-one; great poetry publish |
Slower than uv; its own [tool.poetry]-era conventions linger; resolver historically stricter |
| PDM (2.29.x) | Projects + PEP 621/PEP 582 natives | pdm.lock (and pylock.toml support) |
pdm python install |
Standards-first crowd; PEP 582 __pypackages__ option |
Smaller community than Poetry/uv; two lock formats to reason about |
| conda / mamba | Packages and Python + non-Python binaries (CUDA, GDAL, R) | conda-lock/explicit specs |
Yes — conda owns interpreters | Data science with binary deps (numpy BLAS, CUDA stacks) | Different ecosystem (conda-forge vs PyPI); heavier; overkill for pure-Python API work |
| uv (0.13.x) | Everything: Python, venvs, projects, tools, scripts | uv.lock (cross-platform, hashed) |
uv python install/list/pin |
This path's default — fast, one tool, PEP 621/735/723 native | Younger than pip; some exotic pip workflows need uv pip or another tool |
The honest summary:
- For application projects (what you will build): uv. It is the only tool here that does interpreter management, project management, tool management and script running in one binary, with a real lockfile and speeds that changed expectations.
- For CLI tools on your machine:
uv tool/uvx(or pipx if uv isn't installed). - For binary-heavy data work (CUDA, system libraries): conda/mamba still owns that niche — uv installs Python packages, not arbitrary system binaries. If a later lesson needs a native lib, that's when conda enters; for LLM API work you won't.
- Poetry/PDM are fine tools in existing codebases — don't rewrite a Poetry project to uv on a whim; do choose uv for anything new.
- pip isn't dead — it's the fallback inside every venv and the interface
uv pipmirrors.
Part 6: Versions and pinning#
6.1 Version specifiers#
A version specifier is the small language inside dependencies = [...] that says which releases are acceptable. The common operators:
| Specifier | Means | Example |
|---|---|---|
==1.2.3 |
Exactly this version | httpx==0.28.1 |
!=1.2.3 |
Any version except this one | pytest!=8.0.0 |
>=1.2 |
This version or newer | pydantic>=2.14 |
<=, >, < |
The obvious bounds | fastapi<1.0 |
~=1.2.3 |
Compatible release (PEP 440): >=1.2.3, <1.3 — the segment before the last digit may not change |
~=9.1.4 allows >=9.1.4,<9.2; ~=9.1 allows >=9.1,<10 |
=== |
Arbitrary equality (rare; for non-standard versions) | — |
pkg[extra] |
The package with an optional extra | uvicorn[standard] |
pkg @ url |
A direct URL or path instead of an index | aitoolkit @ file:///libs/aitoolkit |
Combinations use commas (AND): ">=2.14,<3". || is not a thing — use environment markers for "different rules on different platforms": "numpy>=2; sys_platform == 'win32'" or per-group markers.
6.2 Loose vs tight: libraries and applications pin differently#
This is the single most misunderstood rule in packaging:
- A library (something others import) should declare loose requirements (
httpx>=0.28,<1) so it works across a wide range of consumer environments. Its own lockfile is for its CI only. - An application (something you deploy and run — every project in this path) should pin tightly and commit the lockfile, because "the environment it runs in" is yours alone and reproducibility beats flexibility.
aitoolkit is an application in this sense. To keep the path's commands short, its uv add lines name packages without versions: uv writes a lower bound (httpx>=0.28.1) into pyproject.toml and uv.lock records the exact versions you were given, which is what keeps your environment reproducible. When you deploy an application of your own, you can tighten the specifiers as well (uv add httpx --bounds exact writes an == pin); when you publish a real library, loosen them. The lockfile keeps your own dev environment exact either way.
6.3 Semantic versioning, and its limits#
SemVer (MAJOR.MINOR.PATCH) is the convention most packages follow: PATCH = bug fixes, MINOR = backwards-compatible features, MAJOR = breaking changes allowed. It is a convention, not a law:
- Some projects break rules in minor releases; some are 0.x forever where "anything may break".
- AI SDKs are the extreme case:
openai,anthropicandgoogle-genaiship frequently, and outputs and parameters shift between releases, which is why each lesson in this path says which versions its samples were checked against (03.1, 9.4 and 4.4 there cover the "read the changelog" habit). - Treat
requires-pythonand dependency specifiers as contracts you test against: the only proof a range works is running your tests on both ends of it.
6.4 Upgrading deliberately, checking for staleness, auditing#
uv lock --upgrade-package httpx # move ONE package, keep the rest pinned
uv lock --upgrade # move everything the specifiers allow
uv sync # apply
uv tree # see what the upgrade pulled inThen run your tests before committing uv.lock. For "what's outdated":
uv pip list --outdated # against the active/--python env (pip interface)
uv lock --upgrade --dry-run # preview what a full upgrade would changeSecurity auditing. Two tools, both querying the OSV vulnerability database:
uv audit(preview as of November 2026): scans the locked environment for known vulnerabilities and "adverse" project statuses, 4-10x faster than pip-audit per Astral's announcement, with--output-format json|sariffor CI. Opt-in malware check:UV_MALWARE_CHECK=1 uv syncaborts installs containing known-malicious releases.pip-audit(PyPA, 2.10.x): the established scanner;pip-auditoruvx pip-auditboth work.
Run one in CI and before releases; triage findings (a vulnerable transitive dep you don't exercise may be acceptable risk — document it). Deeper supply-chain treatment lives in 12.7.
Supply-chain hygiene, the habits that matter day-to-day:
- Pin exact versions for anything deployed; commit
uv.lock(it carries hashes, so a swapped PyPI file fails verification). - Prefer well-known packages; a typosquat (
reqeusts,httpx2-lookalikes) is indistinguishable until it isn't — the defences are review,uv treereading, and private indexes. - Slopsquatting is the AI-era variant. Coding assistants and chat models sometimes suggest a package name that does not exist; attackers register those hallucinated names and wait for someone to
uv addthem. Before adding anything an assistant recommended, open its PyPI page and check the project's age, release history, repository link and download numbers, and compare the spelling with the library's own documentation. - A cooldown on brand-new releases. Malicious releases are often (not always) reported within days of publication. uv's
exclude-newersetting limits resolution to files uploaded before a date, and accepts a duration too ([tool.uv] exclude-newer = "7 days"), so a freshly published release is not picked up the moment it appears (per the settings reference, as of November 2026;exclude-newer-packageexempts or overrides single packages). It affects new resolutions: an existinguv.lockkeeps its pinned versions, and an urgent security fix may need a per-package exemption. uv.lockrecordssdist/wheelhashes: tampering with a published file breaksuv sync. Don't pass--no-verify-hashesequivalents casually.- Renovate/Dependabot can propose upgrades as PRs (uv's integration docs list the setup); review the changelog, run tests, merge deliberately — the same discipline as
uv lock --upgrade-packageby hand.
Part 7: Project layout and the aitoolkit skeleton#
7.1 Flat vs src/ layout#
Two camps exist:
flat/ src/
├── pyproject.toml ├── pyproject.toml
├── aitoolkit.py or aitoolkit/ ├── src/
└── tests/ │ └── aitoolkit/
└── tests/src/ layout is the recommendation for anything installable, and uv init produces it by default. The reason is subtle and important: with a flat layout, import aitoolkit can accidentally pick up your source folder instead of the installed package when you run from the project root — tests then pass against code that was never installed, and "it works on my machine" returns in a new form. With src/, the package is only importable after installation, so tests exercise the real artefact. uv sync installs the project itself into .venv (that's why import aitoolkit just works after uv sync).
7.2 The standard tree#
aitoolkit/
├── .git/ # created by uv init / git init — never commit by hand
├── .venv/ # the project environment — gitignored, rebuilt by uv sync
├── .env # secrets — gitignored (01B.2 owns this file's rules)
├── .env.example # committed template — names only, no values
├── .gitignore
├── .python-version # "3.13"
├── Makefile # task shortcuts (make test, make lint) — or justfile
├── README.md
├── pyproject.toml # metadata + deps + tool config
├── uv.lock # exact resolution — committed
├── data/ # small local datasets/fixtures (large data → object storage)
├── scripts/ # operational scripts: seed, migrate, one-off jobs
├── src/
│ └── aitoolkit/ # THE package
│ ├── __init__.py # __version__ lives here
│ └── py.typed # tells type checkers "we ship types" — `uv init --lib` creates it,
│ # `--package` does NOT, so 7.4 adds it with `touch` ([8.2](#82-type-checkers))
└── tests/ # mirrors src/: tests/test_settings.py etc.
└── conftest.py # shared pytest fixtures (01B.8 owns pytest)Conventions worth adopting immediately:
tests/at the root, not insidesrc/— keeps test code out of the shipped wheel.scripts/for things you run but don't ship (uv run python scripts/seed.py).data/for small committed fixtures; anything big or sensitive goes elsewhere..env+.env.examplepair — 01B.2 owns the full treatment; the skeleton just creates them.Makefile(orjustfile) somake test/make lint/make syncwork identically for everyone — the tasks are thin wrappers overuv run ...commands you'll learn here.
7.3 pyproject.toml in full#
After uv init aitoolkit --package --python 3.13 and adding this module's dependencies, the file the later lessons build on looks like this. The listing shows bare package names. Your own uv add commands in 7.4 name the packages without versions, so uv writes a lower bound such as httpx>=0.28.1 for each one into your file, and your uv.lock records the exact versions uv resolved on the day:
# pyproject.toml — the aitoolkit project manifest
[project]
name = "aitoolkit"
version = "0.1.0"
description = "Shared toolkit for the AI engineering path"
requires-python = ">=3.13"
dependencies = [
"fastapi[standard]",
"httpx",
"pydantic",
"pydantic-settings",
"python-dotenv",
"tenacity",
"uvicorn",
]
[dependency-groups]
dev = [
"pytest",
"pytest-asyncio",
"respx",
"ruff",
]
[project.scripts]
aitoolkit = "aitoolkit.cli:main" # the CLI arrives in 01B.10; harmless until then
[build-system]
requires = ["uv_build>=0.13.7,<0.14.0"] # uv writes this bound for its own version
build-backend = "uv_build"
[tool.ruff]
line-length = 100
target-version = "py313"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "ASYNC", "S"]
[tool.ruff.lint.per-file-ignores]
"tests/**" = ["S101", "S105", "S106", "S107"]
[tool.pytest.ini_options]
testpaths = ["tests"]
asyncio_mode = "auto"
addopts = "-q"
[tool.uv]
package = true # install the project itself into .venvField notes:
[dependency-groups] dev(PEP 735) is installed byuv syncby default;uv sync --no-devexcludes it (useful for production images that shouldn't carry pytest).[project.optional-dependencies]is the other mechanism — extras like[project.optional-dependencies] dev = [...]ship with the package for consumers. For an application, dependency-groups are the right home for dev tools; extras matter when you publish.[tool.uv] package = trueis belt-and-braces for--packageprojects; uv infers it from[build-system]anyway.- The ruff/pytest tables are explained in Part 8; they live here so the project is configured once. The pytest table's
addopts = "-q"is only a starting value: 01B.8, 2.4 replaces that one line (it does not add a second key), and 01B.10, 4.3 shows the final table. per-file-ignoresexemptstests/**fromS101("assert used") andS105–S107(hardcoded-secret-looking strings). Ruff'sSfamily can't tell test code from shipped code — a pytest suite is nothing butasserts, and test fakes legitimately pass key-shaped strings — so without the exemptionuv run ruff check .would fail on idiomatic tests from 01B.8 onward.fastapi[standard]is FastAPI plus the batteries its CLI, test client and uploads need (uvicorn[standard],fastapi-cli,python-multipart,httpx2forTestClient); 01B.7 lists exactly what it pulls in. Barefastapiwould also run, butfastapi dev, file uploads andTestClientwould each need something extra.- Deliberately absent for now:
numpy,pandas,pyyaml— later lessons add them withuv addwhen they're first needed, keeping this skeleton minimal until then. uv add/uv removeeditdependencies/groups for you — prefer them over hand-editing, though hand-editing is legal TOML and uv respects it on the next sync.
7.4 Creating the skeleton#
uv init aitoolkit --package --python 3.13
cd aitoolkit
git init # if uv didn't already (it does outside a repo)
uv add "fastapi[standard]" httpx pydantic \
pydantic-settings python-dotenv tenacity uvicorn
uv add --dev pytest pytest-asyncio respx ruff
mkdir -p tests scripts data
touch src/aitoolkit/py.typeduv init --package has already created src/aitoolkit/__init__.py, pyproject.toml, README.md and .python-version (uv's project-init page lists exactly those for a packaged project; only --lib adds py.typed, so the touch creates the empty marker file); the mkdir adds the other folders from 7.2. Two edits to pyproject.toml finish the skeleton, and you make them by hand because uv add only touches the dependency lists. First, uv init wrote aitoolkit = "aitoolkit:main" under [project.scripts], and the minimal __init__.py below no longer defines main, so change that line to aitoolkit = "aitoolkit.cli:main" as in 7.3 (the aitoolkit.cli module arrives in 01B.10; until then nothing calls the script). Second, paste in the [tool.ruff], [tool.ruff.lint], [tool.ruff.lint.per-file-ignores] and [tool.pytest.ini_options] tables from 7.3. Leave [build-system] as uv wrote it. If you add [tool.uv] package = true as well, that is harmless.
The \ line continuations are bash syntax — in PowerShell, join each uv add onto a single line (or end lines with a backtick ` instead).
Then create .env.example and .gitignore (the .env rules are 01B.2's; the .gitignore must at minimum contain):
# .gitignore
.env*
!.env.example
.venv/
__pycache__/
*.py[cod]
.pytest_cache/
.ruff_cache/
dist/
*.egg-info/Verify the ignore rules actually work — this is a real run from a scratch git repo (deterministic output):
git add -A
git status --short
# -> A .env.example
# A .gitignore
# A main.py (.env was NOT staged)
git check-ignore -v .env .venv/x.py __pycache__/m.pyc .env.example
# -> .gitignore:2:.env* .env
# .gitignore:4:.venv/ .venv/x.py
# .gitignore:5:__pycache__/ __pycache__/m.pyc
# (.env.example printed nothing: the !.env.example negation un-ignores it).env never reached the index; .env.example did — exactly the contract 01B.2 relies on.
src/aitoolkit/__init__.py starts minimal (later lessons add the real modules):
# src/aitoolkit/__init__.py
"""aitoolkit — the shared Python toolkit for the AI engineering path."""
__version__ = "0.1.0"Smoke-test the whole setup:
uv run python -c "import aitoolkit; print(aitoolkit.__version__)"
# -> 0.1.0
uv run pytest # exits 5 ("no tests collected") until 01B.8 lands tests — expected, not a setup bug
uv run ruff check . # cleanPart 8: Developer tooling#
Deep-dive
A project isn't done when it runs — it's done when it's maintainable: linted, type-checked, tested and runnable by one command. This part wires the standard toolchain into pyproject.toml once, so every later lesson inherits it.
8.1 ruff: linting and formatting in one binary#
Ruff (current release 0.17.x as of November 2026, https://pypi.org/project/ruff/) is Astral's Rust linter + formatter — it replaces flake8, isort, pyupgrade, pycodestyle and dozens of plugins at ~100x the speed. It is already a dev dependency in the skeleton (ruff).
uv run ruff check . # lint
uv run ruff check --fix . # lint + apply safe fixes
uv run ruff format . # format (like black)
uv run ruff format --check . # CI: fail if not formatted
uvx ruff@latest check . # try the newest ruff without installing itThe [tool.ruff] config from 7.3 selects rule families: E/W (pycodestyle errors/warnings), F (pyflakes — unused imports, undefined names), I (isort import sorting), UP (pyupgrade — modernise to 3.11+ idioms), B (bugbear — likely bugs), ASYNC (async-specific pitfalls), S (bandit-style security checks — flags assert anywhere it appears, hardcoded secrets, weak hashes, pickle; the tests/** exemption for the assert/secret rules lives in per-file-ignores, explained in 7.3). Add families as needed; ruff rule <CODE> explains any rule.
8.2 Type checkers#
Python's type hints (from 01A.10) are only useful if something checks them. The landscape as of November 2026:
| Checker | Maintainer | Status | Speed | Notes |
|---|---|---|---|---|
| mypy (2.4.x) | Python core team tradition (Dropbox origin) | Production-stable | Moderate | The reference implementation; strictest ecosystem of plugins/stubs |
| Pyright (1.1.x) | Microsoft | Production-stable | Fast | Powers Pylance in VS Code; basedpyright (1.40.x) is a community fork with extra strictness |
| ty (0.0.x) | Astral | Beta | Very fast (Rust) | New; 10-100x faster than mypy/Pyright per its docs; uv integration is experimental (uv check preview) |
| Pyrefly (1.4.x) | Meta | Beta/preview | Very fast (Rust) | Newer entrant; focused on large codebases |
For this path the pragmatic choice: use what your editor already runs (VS Code's Pylance/Pyright is the default Python experience), add ty or mypy to CI for the gate, and keep type hints accurate rather than exhaustive. Install any of them as a dev dependency (uv add --dev ty / mypy / basedpyright) or run ad hoc with uvx ty check / uvx mypy .. The empty py.typed marker in src/aitoolkit/ (you created it with touch in 7.4; uv's --lib template would have added it, --package does not) tells checkers your package ships real types; keep it even though you're an app.
uv add --dev ty # or: uvx ty check .
uv run ty check src tests # type-check the package and tests8.3 pre-commit hooks#
pre-commit (4.7.x) is the framework that runs checks before a commit exists: ruff, the type checker, whitespace fixers, secret scanners — each pinned, each in its own environment, defined once in .pre-commit-config.yaml:
# .pre-commit-config.yaml
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.17.4
hooks:
- id: ruff
args: [--fix]
- id: ruff-format
- repo: local
hooks:
- id: ty
name: ty
entry: uv run ty check
language: system
types: [python]uv tool install pre-commit # or: uvx pre-commit
pre-commit install # one-time: wire the git hook
pre-commit run --all-files # run everything nowThe value isn't the tool — it's that the check runs on your machine before the bad code is even committed, and the same config runs in CI. 01B.8 adds a secret-scanning hook (detect-secrets or gitleaks awareness) once .env handling matters.
8.4 Editor integration#
VS Code (covered in 00.1, Part 4) needs two things to feel magical in a uv project:
- The right interpreter: Cmd/Ctrl+Shift+P → "Python: Select Interpreter" → pick
.venv/bin/pythoninside the project (or install the uv-aware Python extension, which finds it). Wrong interpreter = "import could not be resolved" and type errors that aren't real — the #1 fresh-project confusion (11.1). - Extensions: the Python extension (Pylance), Ruff (runs
ruff check/formaton save), and pytest (discovers and runs tests inline). All free.
Other editors: PyCharm/IntelliJ has first-class uv support; Neovim/Emacs users configure their LSP servers the same way (ty and ruff both ship language servers).
8.5 pytest: the preview#
pytest (9.2.x) is the test runner every later lesson uses. This lesson only installs it (pytest, pytest-asyncio and respx in the dev group); 01B.8 owns it properly. For now, know that uv run pytest discovers tests/test_*.py, and the [tool.pytest.ini_options] table in pyproject.toml already points it at tests/.
8.6 EditorConfig and the Makefile#
EditorConfig (.editorconfig) gives every editor the same basics — indent style, line endings, trailing whitespace — independent of language tooling:
# .editorconfig
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 4
[*.{yml,yaml,toml}]
indent_size = 2Makefile (or justfile if you prefer a modern runner) gives the project its verbs — thin wrappers so nobody memorises uv flags:
# Makefile — the project's task list
.PHONY: sync run pytest pytest-cov test lint format check
sync: ; uv sync
run: ; uv run python # drops into the project interpreter
test: pytest
pytest: ; uv run pytest
pytest-cov: ; uv run pytest --cov=aitoolkit --cov-report=term-missing
lint: ; uv run ruff check .
format: ; uv run ruff format .
check: lint test # the pre-merge habitmake sync && make test && make lintmake pytest-cov needs the pytest-cov plugin, which is not in this skeleton's dev group yet; 01B.8 adds it (uv add --dev pytest-cov), and 01B.10 carries it in the consolidated pyproject.toml. The other targets work now.
Part 9: Notebooks and scratch work#
Deep-dive
9.1 When notebooks help — and their traps#
Jupyter notebooks (.ipynb), VS Code's notebook editor, and marimo (a newer reactive notebook that stores code as plain .py files — worth knowing as of November 2026) are genuinely useful for exploration: prototyping a prompt, eyeballing an API response, trying three embedding configs side by side. For AI work specifically, notebooks are how people poke at model outputs before writing the pipeline.
The traps are reproducibility ones:
- Hidden state: cells run in order, but you can re-run cell 5 without re-running cell 2 — the notebook then shows answers computed from a state that no longer exists. "Restart and run all" before trusting anything.
- No dependency declaration: a notebook that
import pandasdoesn't say which pandas. The fix is the project environment as the kernel (below) plus, for real scripts, PEP 723 metadata. - Outputs in git: committed notebooks carry stale outputs and can leak data. Treat them as scratch; commit the script version when it stabilises.
uv has first-class integrations: uv run --with jupyter jupyter lab or the docs' Jupyter guide / marimo guide. The key habit: point the notebook kernel at the project's .venv, so import httpx in a cell resolves to the version locked for the project, not whatever your global Python has. In VS Code: pick .venv/bin/python as the kernel. In Jupyter: uv run --with notebook jupyter notebook inside the project, or register the project env as a named kernel — the Jupyter guide's recipe is uv add --dev ipykernel first, then uv run ipython kernel install --user --env VIRTUAL_ENV "$(pwd)/.venv" --name=aitoolkit (bash form; --env VIRTUAL_ENV tells ipykernel to read the env path from the variable uv run sets).
9.2 Scratch work: uv run --with#
For throwaway experiments that need a package but aren't worth a project:
uv run --with pandas python explore.py # pandas available for this run only
uv run --with 'httpx==0.28.1' --with rich python demo.py
uv run --no-project --with numpy python bench.py # outside any projectuv builds an ephemeral cached environment per combination of requirements — no pip install into your project, no pollution, reproducible because the versions are in the command. When the scratch work graduates to real code, move the deps into pyproject.toml via uv add.
Part 10: Docker and CI previews#
Reference
These are previews only — 11C.1 owns production Docker and 11C.2 owns CI/CD. The point here is that your uv project drops into both cleanly.
10.1 Docker#
uv publishes an official image (ghcr.io/astral-sh/uv) and documents a Docker guide. The pattern for a Python service:
# Dockerfile — illustrative; 11.9 owns the production version
FROM python:3.13-slim
COPY --from=ghcr.io/astral-sh/uv:0.13.7 /uv /uvx /bin/
WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN uv sync --locked --no-dev --no-install-project
COPY README.md ./
COPY src ./src
RUN uv sync --locked --no-dev
CMD ["uv", "run", "--no-sync", "uvicorn", "aitoolkit.service:app", "--host", "0.0.0.0"]Why each line: COPY README.md is there because the project's pyproject.toml declares readme = "README.md" and the uv_build backend reads that file when it builds the project's metadata (the backend's source, metadata.rs in the astral-sh/uv repository, shows it reading the readme path as of November 2026, so a missing file fails the build); uv sync --locked proves the committed lockfile installs cleanly in the image (same guarantee as CI); --no-dev keeps pytest/ruff out of production; --no-install-project before copying source avoids rebuilding on every code change (layer caching); uv run --no-sync runs without re-checking. Pin the uv image tag to the version your lockfile was made with.
10.2 CI (GitHub Actions)#
The astral-sh/setup-uv action installs uv in CI; the whole pipeline is three steps:
# .github/workflows/ci.yml — illustrative; 11.10 owns the real pipeline
name: ci
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
version: "0.13.7"
python-version: "3.13"
- run: uv sync --locked
- run: uv run pytest
- run: uv run ruff check .uv sync --locked fails the build if uv.lock is stale — the single most valuable CI habit this lesson teaches. Cache is automatic via setup-uv (enable-cache defaults to auto: on for GitHub-hosted runners, off for release/tag-push events). One supply-chain note: setup-uv no longer publishes floating major tags beyond v7, so the snippet pins the action to a commit SHA with a version comment — the README's own recommended form; check the repo's releases for the current pin when you copy this.
Part 11: Troubleshooting and the failure gallery#
Reference
11.1 The troubleshooting table#
| Symptom | Likely cause | Fix |
|---|---|---|
uv add fails with a wall of text ending "No solution found ... depends on Python>=3.11" |
requires-python inferred from an old system Python at uv init (the --python 3.13 trap, 4.2) |
Set requires-python = ">=3.13" in pyproject.toml (and .python-version), re-run uv add |
ModuleNotFoundError: No module named 'x' right after install |
Wrong interpreter: editor/terminal using system Python, not .venv |
Use uv run ... (always correct), or select .venv/bin/python in the editor |
error: externally-managed-environment on pip install |
Distro/Homebrew Python refuses global installs | Use a venv — uv sync handles it; never --break-system-packages |
The lockfile at uv.lock needs to be updated |
pyproject.toml changed without uv lock/uv sync |
uv lock (or just uv sync/uv add which lock automatically) |
uv sync --locked fails in CI but worked locally |
Someone edited pyproject.toml without committing uv.lock |
Run uv lock, commit both files |
SSL / certificate errors during uv sync |
Corporate proxy inspecting TLS; missing CA certs | uv uses OS trust store; install ca-certificates in slim images or set SSL_CERT_FILE/SSL_CERT_DIR; --native-tls/--allow-insecure-host are last resorts |
Package installs but import fails on Apple Silicon / ARM |
sdist-only package with no arm64 wheel | Check uv tree; prefer wheels; report upstream; uv pip install --no-binary is rarely the fix |
Filename too long / path errors on Windows |
Long paths + deep .venv |
Enable Windows "LongPathsEnabled" or move project closer to drive root |
uv run is slow every time |
Syncing because pyproject.toml/uv.lock drifted, or huge dep tree |
Expected once; uv sync once then uv run is fast; check uv tree for accidental heavy deps |
Two projects want different httpx versions |
Installing into shared/global env | Never — each project has its own .venv; that's the point of Part 2 |
git status shows .env or .venv changes |
.gitignore missing or wrong |
Add the 7.4 entries; verify with git check-ignore -v |
| Notebook kernel can't import project packages | Kernel pointed at system Python | Select .venv/bin/python as the kernel (9.1) |
pre-commit hook fails but CI passes |
Hook env differs from project env | Use language: system + uv run in the hook, or uv tool install pre-commit |
11.2 The failure gallery#
Real-shaped failures this lesson exists to prevent:
- Global pollution:
pip install openaiinto system Python → every project now shares one version; the nextpip installdowngrades it for someone else. Fix: never install project deps outside.venv. - The stale lock: teammate pulls, runs
uv sync --frozen, gets last month's versions becauseuv.lockwasn't committed. Fix: commituv.lock— always. - The phantom dependency: code does
import requestsbutrequestswas never declared — it worked because another package happened to pull it in transitively. The day that package drops it, your code breaks. Fix:uv add requests— declare what you import.uv pip checkfinds the reverse problem (conflicting requirements). - The hand-edited lock: someone "fixed"
uv.lockby hand; nextuv sync --lockedfails cryptically. Fix: never edit generated files; changepyproject.tomland re-lock. - The unpinned tool:
uvx rufffloats to whatever's newest — a new ruff release rewrites your style overnight. Fix:uvx ruff@0.17.4or pin inpyproject.toml/pre-commitconfig. - The
--frozentrap: CI uses--frozento "save time" and silently installs a stale lock forever. Fix:--lockedin CI (it checks),--frozenonly for reproducing a known-good artefact.
Common misconceptions#
| Misconception | Reality |
|---|---|
"pip install into the system Python is fine for learning." |
It works until two projects need different versions of the same package — then everything breaks at once. A venv costs one command. |
"requirements.txt and uv.lock are the same thing." |
requirements.txt is an input (what you want); a lockfile is the resolved output (what you got, exactly, with hashes). uv reads the first to write the second; you commit the second. |
"I need to source .venv/bin/activate before uv run." |
No — uv run already executes inside .venv. Activation is the old workflow; uv run replaces it. |
"uv add httpx and uv add httpx==0.28.1 do the same thing." |
No — bare uv add writes a lower bound (httpx>=0.28.1), not an exact pin. For a deployed application, write == yourself or pass --bounds exact; the lockfile is what keeps day-to-day installs exact. |
".python-version and requires-python are duplicates." |
They answer different questions: the file pins which interpreter uv prefers; the field constrains which versions are allowed (and which dependency wheels resolve). |
"The dev dependency group is only for tests." |
It's for all development-only tooling: pytest, ruff, type checkers, docs builders. Production installs use uv sync --no-dev. |
"uv.lock is auto-generated so I don't need to commit it." |
The opposite — it's the artefact that makes installs reproducible. Uncommitted lock = "works on my machine" returns. |
| "Notebooks need their own environment." | They need the project's environment as the kernel — a separate env is how you get pandas 1.x in a notebook and pandas 3.x in production. |
"uv is just a faster pip." |
It also installs Python, manages projects/lockfiles, runs tools (uvx) and scripts (PEP 723). pip is one layer of what it replaces. |
| "Pinning exact versions is always safest." | For libraries you publish, loose specifiers are correct — tight pins in a library's dependencies break your consumers. Pin tightly in applications, loosely in libraries. |
"uv sync --frozen is safer than --locked." |
--locked verifies the lock matches pyproject.toml (catches stale locks); --frozen skips the check entirely (reproduces whatever's committed, even if wrong). CI wants --locked. |
Key takeaways#
- Reproducibility is a contract:
pyproject.tomldeclares intent,uv.lockrecords the exact resolution (with hashes),.venvis the disposable environment that contract installs into. Commit the first two, never the third. - uv does everything: Python installs (
uv python), projects (uv init/add/remove/sync/lock/run/tree/export), tools (uv tool/uvx), scripts (PEP 723 +uv run), and a pip-compatible layer (uv pip) for everything else. - Always pass
--python 3.13touv init— omitting it lets an old system Python setrequires-pythontoo low and breaksuv addlater. uv runreplaces activation: it syncs.venvto the lockfile before every command, souv run pytest/uv run uvicorn/uv run pythonare the only commands you need.- Pin like an application: exact versions in
dependencies, committeduv.lock, deliberate upgrades viauv lock --upgrade-package, audits viauv audit/pip-audit. src/layout + dependency-groups + tool tables inpyproject.tomlis the modern Python project shape; theaitoolkitskeleton in Part 7 is the one every later lesson extends.- Tooling is configuration, not ceremony: ruff, a type checker, pre-commit, pytest and EditorConfig wired once in
pyproject.toml/dotfiles pay off in every subsequent lesson.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Virtual environment (venv) | A private folder (.venv/) holding a project's own Python packages, isolated from the system interpreter |
| Site-packages | The directory inside an environment where third-party packages are installed |
pyproject.toml |
The project manifest (PEP 621 [project] table + [tool.*] config) every modern tool reads |
| PEP 621 | The standard that defined [project] metadata in pyproject.toml |
| PEP 735 | The standard for [dependency-groups] — named dependency sets like dev |
| PEP 723 | Inline script metadata: a # /// script TOML block declaring a single file's deps |
| PEP 440 | The version-specifier spec (==, >=, ~=, !=, markers) |
| PEP 508 | The requirement-string format used in dependencies (name[extra]>=1.0; marker) |
Lockfile (uv.lock) |
The generated file recording exact resolved versions + hashes for every dependency |
| Resolver | The algorithm that picks one compatible version for every package from specifiers |
| Transitive dependency | A dependency of a dependency — the reason lockfiles exist |
Wheel (.whl) |
The prebuilt package format pip/uv install (a zip with code + metadata) |
| sdist | Source distribution — the package's raw source, built on install when no wheel exists |
| PyPI | The Python Package Index, the default package repository |
| Index | A package repository URL a resolver queries (PyPI, private mirrors) |
src/ layout |
Package code under src/ so imports only resolve after installation |
| Editable install | Installing the project so edits take effect without reinstall (uv sync does this for the project itself) |
| Dependency group | A named set of requirements installed on demand (dev, docs) — PEP 735 |
| Optional dependency / extra | A [project.optional-dependencies] set shipped for consumers (uvicorn[standard]) |
requires-python |
The project's Python-version constraint in pyproject.toml |
.python-version |
The file pinning which interpreter uv prefers for a project |
uv tool / uvx |
Installing/running CLI applications in isolated tool environments |
| Workspace | A multi-package repo sharing one lockfile and .venv ([tool.uv.workspace]) |
uv pip |
uv's pip-compatible interface for arbitrary environments |
--locked / --frozen |
Sync modes: verify-then-install vs install-the-committed-lock-as-is |
| SemVer | MAJOR.MINOR.PATCH versioning convention (a convention, not enforced) |
Compatible release (~=) |
PEP 440 specifier meaning "same prefix, patch may rise" |
| Environment marker | A ; sys_platform == '...' condition on a requirement |
| Hash checking | Verifying downloaded files against lockfile-recorded hashes |
| Typosquatting / slopsquatting | Registering lookalike package names to ship malicious code |
| pre-commit | The framework running checks (ruff, type check) before each commit |
| Linter / formatter | Static style+bug checks / automatic layout rewriting (ruff does both) |
| Type checker | Static verification of type hints (mypy, Pyright, ty, Pyrefly) |
py.typed |
Marker file telling type checkers the package ships real types |
PEP 751 (pylock.toml) |
The standard lockfile format uv can also export |
| SBOM (CycloneDX) | Software bill of materials — uv export --format cyclonedx1.5 |
All terms are also collected in the glossary.
Exercises#
Work through these in order — they build the aitoolkit project this module uses.
- Create and inspect. Run
uv init playground --package --python 3.13 && cd playground && uv sync. List every fileuv initcreated (find . -not -path './.git/*' -not -path './.venv/*' | sort). Which did--bareskip? Repeat with--barein a second folder and diff the two trees. - The
--pythontrap. Create a project without--pythonon a machine whose firstpython3is old (uv python listtells you what's installed). Inspect the generatedrequires-python. Fix it to>=3.13and re-runuv add httpx. - Dependencies. In
playground:uv add httpx,uv add --dev pytest ruff,uv remove httpx. After each, checkpyproject.toml,uv.lockanduv tree. Which files changed each time? - Lockfile reading. Open
uv.lockand find the[[package]]entries forhttpxand its dependencies. Identify theversion,source, andsdist/wheels+hashfields. Then runuv export --format requirements.txtand compare. - Locked vs frozen. Hand-edit
pyproject.tomlto add"rich"todependencieswithout runninguv lock. Runuv sync --locked— paste the error. Runuv lock && uv sync --locked— explain why the second succeeds. - PEP 723 script. Create
titles.pyoutside any project with a# /// scriptblock (requires-python = ">=3.11",dependencies = ["httpx"]) and amain()that fetches one URL. Runuv add --script titles.py richand inspect the block it writes. Thenuv run titles.py. Copy the file into theaitoolkitproject and compareuv run titles.py(script metadata wins) withuv run --no-project python titles.py(no project env either) — explain which environment each used. - Specifier practice. For each, write the expanded range:
~=2.14.3,~=2.14,>=1.0,<2,!=1.5.*. Which would you choose for an application pin vs a library requirement, and why? - venv probe. Create
.venvwithpython3 -m venv, run thevenv_probe.pysnippet from 2.3 inside and outside, and confirmsys.prefix/sys.base_prefixbehave as described. - gitignore audit. In a scratch git repo, write the
.gitignorefrom 7.4, create.env,.env.example,.venv/fake.py,src/x.py, rungit add -A && git status --shortandgit check-ignore -von each path. Which files got staged? - Layout decision. Convert a flat-layout toy (
main.py+mypkg/at root) tosrc/layout. Show thatimport mypkgfails beforeuv syncinstalls it and works after — and explain why that failure is a feature. - Tool vs project dep. Install
ruffboth ways:uv tool install ruffanduv add --dev ruff. Runwhich ruffvsuv run ruff --version. Why can both coexist at different versions? - Upgrade discipline. Pick one dev dependency, run
uv lock --upgrade-package <pkg> --dry-run, read what would change, then decide whether to apply it. What doesuv lock --upgrade(no package) risk that--upgrade-packagedoesn't? - Audit awareness. Run
uv audit(preview) oruvx pip-auditagainst theaitoolkitenv. If findings appear, identify whether they're direct or transitive deps and whatuv lock --upgrade-packagecould fix.
Solutions
- Default
uv initcreates.git/,.gitignore,.python-version,pyproject.toml,README.md,src/playground/__init__.py.--barecreates onlypyproject.toml(verified in 4.2). - Without
--python,requires-pythonreflects the first interpreter uv finds (e.g.>=3.9);uv addof a>=3.11package then fails resolution. Setrequires-python = ">=3.13"and.python-versionto3.13, thenuv addworks. uv addappends todependencies+ re-locks + syncs;--devwrites to[dependency-groups] dev;uv removedeletes fromdependencies,uv.lockand.venv— and from a group only when you pass--group/--dev(plainuv remove pytesterrors on a dev-only package).uv treeshows the resolved graph.- Each
[[package]]hasname,version,source = { registry = "https://pypi.org/simple" },dependencies,sdist/wheelswithurl+hash, andresolution-markers.uv exportrenders the same pins asname==versionlines plus a header. uv sync --lockedfails: "The lockfile atuv.lockneeds to be updated, but--lockedwas provided." Afteruv lock,--lockedpasses because the lock now matchespyproject.toml.uv add --script titles.py richappends"rich"to the# /// scriptblock. Outside a project,uv run titles.pyuses the script's ephemeral env (httpx + rich). Insideaitoolkit,uv run titles.pystill uses the script's env — PEP 723 metadata wins over project deps — whileuv run python titles.pyuses the project env (script metadata is only read when the.pyfile is the command), anduv run --no-project python titles.pyruns in a bare interpreter env with neither project's nor script's packages guaranteed.~=2.14.3→>=2.14.3,<2.15;~=2.14→>=2.14,<3;>=1.0,<2→>=1.0,<2.0;!=1.5.*→ any version except the 1.5 series. Applications:==pins; libraries:>=x,<yranges.- Inside
.venv:prefix == base_prefix -> False,prefix ends with .venv -> True; outside:True. The venv layers on the base interpreter. - Staged:
.env.example,.gitignore,src/x.py. NOT staged:.env(matched.env*),.venv/fake.py(.venv/),__pycache__if created.git check-ignore -vprints the matching pattern per path. - After moving the package under
src/,import mypkgfrom the project root fails withModuleNotFoundErroruntiluv syncinstalls it — proving tests exercise the installed artefact, not the source tree. uv tool install ruffputsruffon PATH globally (isolated);uv add --dev ruffpins it in the project env.which ruff→ tool env;uv run ruff→ project env. They coexist because they live in different environments.--dry-runshows candidate changes without writing.--upgradere-resolves everything the specifiers allow (a breaking transitive bump can sneak in);--upgrade-packagemoves only the named package and what it forces.uv auditreports known vulnerabilities in the locked env; check whether each is direct (dependencies) or transitive (uv treereveals the parent), thenuv lock --upgrade-package <parent>or accept+document the risk.
Where you'll use this in the AI path#
This lesson is the substrate every later module assumes. The exact places it pays off:
- 03.1, Part 4 — the Module 03 project setup is this lesson's workflow applied to the
llm-apisfolder (--barevariant,uv addof the SDKs,uv run, the lockfile discipline of 4.4 there). - Every 01B lesson —
settings.py(01B.2),http.py(01B.5),models.py(01B.6),service.py(01B.7),resilience.py(01B.9),tests/(01B.8) all land in theaitoolkitskeleton built here. - 03.10 — testing LLM code assumes the pytest/fixture/tooling setup from Parts 7-8 is already in place.
- 11C.1 and 11C.2 — the Docker and CI previews here become the production pipeline;
uv sync --lockedis the exact command their workflows use. - 12.7 — dependency pinning, lockfile hashes and
uv audit/pip-auditare the first line of supply-chain defence this lesson installs. - 05.1 — ingestion pipelines are exactly the kind of project where a locked, reproducible env matters most (the glossary already credits it with
dependency-groups).
Check yourself#
- What are the three root causes of "works on my machine"?Dependency conflicts (shared global env), version drift (unpinned "latest"), and undeclared state (no record of exact versions).
- What does
sys.base_prefixpoint to inside a virtual environment, and what does that tell you about how venvs work?The real interpreter's home — the venv layers on top of it, sharing the stdlib but not site-packages. - Which
uv initflag creates onlypyproject.toml, and when would you choose it?--bare— for script/dependency folders that aren't installable packages (like Module 03'sllm-apis). - What's the difference between
requires-pythonand.python-version?requires-pythonconstrains which versions are allowed;.python-versionpins which interpreter uv prefers. uv add httpx(no version) writes what topyproject.toml— and is that what an application wants?httpx>=0.28.1(a lower bound) — applications wanthttpx==0.28.1plus the committed lock.- Why is
uv.lockcommitted but.venvnot?uv.lockis the reproducible record everyone installs from;.venvis disposable and rebuilt byuv sync. uv sync --lockedvsuv sync --frozen: which verifies the lock is fresh, and which just installs it?--lockedverifies freshness then installs;--frozeninstalls the committed lock without checking.- What does
uv rundo before executing your command, and why does that make activation unnecessary?It verifiespyproject.toml↔uv.lock↔.venvconsistency and syncs if needed — so the command always runs in the locked environment. - Write the PEP 723 header for a script needing
httpxon Python ≥3.11.# /// script/# requires-python = ">=3.11"/# dependencies = ["httpx"]/# /// ~=9.1.4allows which versions?>=9.1.4, <9.2— the segment before the last digit is fixed.- Why does a library declare loose specifiers while an application pins exactly?Libraries must work across consumers' environments (loose); applications own their environment alone (tight + lock).
- What's the difference between a dependency group and an extra?Groups are dev-side named sets installed on demand (
uv sync --group); extras ship inside the package for consumers (pkg[extra]). - Name two ways
uvcan run a CLI tool without installing it into your project.uvx <tool>(run without permanent install) anduv tool install(isolated global tool env). - Why does
src/layout prevent "tests pass against uninstalled code"?Withsrc/, the package isn't importable until installed —importcan only resolve the installed artefact. - Which single CI command catches a stale
uv.lock?uv sync --locked(oruv lock --check).
Further resources#
- uv documentation — the authoritative reference: projects guide, scripts/PEP 723, pip interface, workspaces, tools, Docker, GitHub Actions.
- PEP 621 (
pyproject.tomlmetadata), PEP 723 (inline script metadata), PEP 735 (dependency groups), PEP 440 (version specifiers) — the standards underneath it all. - pipx, Poetry, PDM, conda — the rest of the landscape, for when you meet them in existing codebases.
- python.org downloads and endoflife.date/python — current versions and support windows.
- uv audit announcement and pip-audit — vulnerability scanning.
- Ruff docs, ty, mypy, Pyright — the toolchain.
- pre-commit, EditorConfig, pytest — the workflow glue.
← Module 01A: Python Essentials | Module 01B overview | 01B.2 — Environment Variables, Configuration and Secrets →