01B.1 Project Setup with uv: Environments, Dependencies and Tooling

FoundationsLesson 1 of 1112,571 words11 parts
Module 01B · 0 of 11 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11

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.toml is (PEP 621), and why you commit a lockfile
  • How to install uv, create projects (uv init and its --bare, --app, --lib, --package and --script modes), and manage them with uv add, uv remove, uv sync, uv lock, uv run, uv tree and uv export
  • How uv manages 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 the uv pip compatibility 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 complete aitoolkit skeleton
  • 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 install and python 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:

bash
curl -LsSf https://astral.sh/uv/install.sh | sh

On Windows, open PowerShell and run uv's documented installer, then open a new terminal so uv is on your PATH:

powershell
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):

bash
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 system

You 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:

  1. Dependency conflicts. Project A needs httpx 0.28, project B needs httpx 0.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.
  2. Version drift. pip install openai with 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: the openai, anthropic and google-genai packages 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 own uv add commands name packages without version numbers, so the protection against drift is the committed uv.lock, which records the exact versions you were given (4.3, Part 6).
  3. Undeclared state. The tutorial's pip install list 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 python program 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 .venv is 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:

python
# 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"))
Output · inside .venv, created with python3 -m venv .venv2 lines
prefix == base_prefix -> False
prefix ends with .venv  -> True
Output · outside, with the system python32 lines
prefix == base_prefix -> True
prefix ends with .venv  -> False

Inside 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:

toml
# 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 = 100

Field 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:

python
# 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"])
Output5 lines
name: aitoolkit
requires-python: >=3.13
deps: ['httpx', 'pydantic']
dev group: ['pytest', 'ruff']
ruff line-length: 100

2.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 --> CODE

A 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):

toml
# 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:

bash
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 installed

This works, and millions of projects use it. Its limits are exactly the problems from Part 1:

  • pip install resolves 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.txt from pip freeze records versions but not the resolution rules — re-installing it is deterministic, but updating it is guesswork.
  • pip installs into whatever environment is active; forget to activate and you pollute your system Python (and then hit externally-managed-environment errors on distro Pythons, covered in 11.1).
  • pip is 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:

text
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:

bash
# 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:

bash
uv --version
Example output · illustrative1 line
uv 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:

bash
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 build

Per 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#

bash
uv init aitoolkit --package --python 3.13
cd aitoolkit

uv 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):

Example output · illustrative1 line
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):

toml
[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 make uv add fail later with a wall of "No solution found" text (11.1 shows that error). Always pass --python 3.13 for this path.
  • uv_build>=0.12.1,<0.13.0 is the build backend pin uv writes for its own version — with uv 0.13.x it writes a 0.13.x bound. Don't hand-edit it; uv manages it.
  • .python-version pins the minor version uv reaches for first; requires-python is the real constraint. Both are committed.
  • --bare creates only pyproject.toml — verified: no .python-version, no .gitignore, no git repo. Module 03's setup relies on this and adds .env/.gitignore by 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#

bash
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 specifiers

What each does, precisely:

  • uv add <pkg> is the command you will use 95% of the time. It appends a PEP 508 requirement to pyproject.toml (respecting --bounds: lower — the default — writes just a lower bound like httpx>=0.28.1; major allows the same major version (>=1.2.3,<2.0.0-style, like semver's caret); minor allows the same minor (>=1.2.3,<1.3.0-style, like semver's tilde); exact pins ==x.y.z — e.g. uv add httpx --bounds exact), re-resolves, rewrites uv.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 targets project.dependencies by 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). Plain uv remove pytest on a dev-only package fails with a hint naming the right flag — the symmetric trap to uv add --dev.
  • uv lock re-runs the resolver and rewrites uv.lock without touching .venv. uv lock --check verifies freshness without writing; uv lock --dry-run shows what would change.
  • uv sync makes .venv match uv.lock exactly: installs missing packages, updates changed ones, and removes extraneous ones (packages in .venv that aren't in the lock). By default it includes the dev dependency group; --no-dev, --only-dev, --group, --no-group, --all-groups, --only-group, --inexact tune that.
  • uv tree prints the resolved tree — the readable answer to "why is certifi installed?" (because httpx needs it).
  • uv export converts the lockfile to other formats for tools that only speak requirements.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 stays uv.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):

console
$ 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'))"
True

And 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):

console
$ 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#

bash
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-is

Before 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: output

4.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:

console
$ 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:

python
# /// 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:

  • dependencies must be present even when empty — a script block without it is invalid (the docs say so explicitly).
  • Inside a project directory, uv run script.py still applies script metadata — the project's dependencies are ignored entirely (uv's docs are explicit that --no-project isn't even required for that). Script metadata is only read when the .py file itself is the command uv runs, so uv run python script.py executes in the project environment instead, while uv run --no-project python script.py gives 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 --script makes 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):

python
# hello.py
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
import sys
print("hello from", sys.version.split()[0])
console
$ 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:

bash
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 ruff

uvx (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:

toml
# 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:

toml
# pyproject.toml
[[tool.uv.index]]
name = "internal"
url = "https://pkgs.example.com/simple"
bash
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:

bash
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 compatibility

uv 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 pip mirrors.

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, anthropic and google-genai ship 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-python and 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#

bash
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 in

Then run your tests before committing uv.lock. For "what's outdated":

bash
uv pip list --outdated              # against the active/--python env (pip interface)
uv lock --upgrade --dry-run         # preview what a full upgrade would change

Security 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|sarif for CI. Opt-in malware check: UV_MALWARE_CHECK=1 uv sync aborts installs containing known-malicious releases.
  • pip-audit (PyPA, 2.10.x): the established scanner; pip-audit or uvx pip-audit both 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 tree reading, 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 add them. 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-newer setting 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-package exempts or overrides single packages). It affects new resolutions: an existing uv.lock keeps its pinned versions, and an urgent security fix may need a per-package exemption.
  • uv.lock records sdist/wheel hashes: tampering with a published file breaks uv sync. Don't pass --no-verify-hashes equivalents 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-package by hand.

Part 7: Project layout and the aitoolkit skeleton#

7.1 Flat vs src/ layout#

Two camps exist:

text
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#

text
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 inside src/ — 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.example pair — 01B.2 owns the full treatment; the skeleton just creates them.
  • Makefile (or justfile) so make test/make lint/make sync work identically for everyone — the tasks are thin wrappers over uv 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:

toml
# 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 .venv

Field notes:

  • [dependency-groups] dev (PEP 735) is installed by uv sync by default; uv sync --no-dev excludes 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 = true is belt-and-braces for --package projects; 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-ignores exempts tests/** from S101 ("assert used") and S105–S107 (hardcoded-secret-looking strings). Ruff's S family can't tell test code from shipped code — a pytest suite is nothing but asserts, and test fakes legitimately pass key-shaped strings — so without the exemption uv 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, httpx2 for TestClient); 01B.7 lists exactly what it pulls in. Bare fastapi would also run, but fastapi dev, file uploads and TestClient would each need something extra.
  • Deliberately absent for now: numpy, pandas, pyyaml — later lessons add them with uv add when they're first needed, keeping this skeleton minimal until then.
  • uv add/uv remove edit dependencies/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#

bash
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.typed

uv 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
# .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):

bash
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):

python
# src/aitoolkit/__init__.py
"""aitoolkit — the shared Python toolkit for the AI engineering path."""

__version__ = "0.1.0"

Smoke-test the whole setup:

bash
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 .  # clean

Part 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).

bash
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 it

The [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.

bash
uv add --dev ty            # or: uvx ty check .
uv run ty check src tests  # type-check the package and tests

8.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:

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]
bash
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 now

The 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:

  1. The right interpreter: Cmd/Ctrl+Shift+P → "Python: Select Interpreter" → pick .venv/bin/python inside 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).
  2. Extensions: the Python extension (Pylance), Ruff (runs ruff check/format on 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:

ini
# .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 = 2

Makefile (or justfile if you prefer a modern runner) gives the project its verbs — thin wrappers so nobody memorises uv flags:

makefile
# 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 habit
bash
make sync && make test && make lint

make 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 pandas doesn'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:

bash
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 project

uv 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
# 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:

yaml
# .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.


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

Real-shaped failures this lesson exists to prevent:

  • Global pollution: pip install openai into system Python → every project now shares one version; the next pip install downgrades 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 because uv.lock wasn't committed. Fix: commit uv.lock — always.
  • The phantom dependency: code does import requests but requests was 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 check finds the reverse problem (conflicting requirements).
  • The hand-edited lock: someone "fixed" uv.lock by hand; next uv sync --locked fails cryptically. Fix: never edit generated files; change pyproject.toml and re-lock.
  • The unpinned tool: uvx ruff floats to whatever's newest — a new ruff release rewrites your style overnight. Fix: uvx ruff@0.17.4 or pin in pyproject.toml/pre-commit config.
  • The --frozen trap: CI uses --frozen to "save time" and silently installs a stale lock forever. Fix: --locked in CI (it checks), --frozen only 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.toml declares intent, uv.lock records the exact resolution (with hashes), .venv is 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.13 to uv init — omitting it lets an old system Python set requires-python too low and breaks uv add later.
  • uv run replaces activation: it syncs .venv to the lockfile before every command, so uv run pytest/uv run uvicorn/uv run python are the only commands you need.
  • Pin like an application: exact versions in dependencies, committed uv.lock, deliberate upgrades via uv lock --upgrade-package, audits via uv audit/pip-audit.
  • src/ layout + dependency-groups + tool tables in pyproject.toml is the modern Python project shape; the aitoolkit skeleton 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.

  1. Create and inspect. Run uv init playground --package --python 3.13 && cd playground && uv sync. List every file uv init created (find . -not -path './.git/*' -not -path './.venv/*' | sort). Which did --bare skip? Repeat with --bare in a second folder and diff the two trees.
  2. The --python trap. Create a project without --python on a machine whose first python3 is old (uv python list tells you what's installed). Inspect the generated requires-python. Fix it to >=3.13 and re-run uv add httpx.
  3. Dependencies. In playground: uv add httpx, uv add --dev pytest ruff, uv remove httpx. After each, check pyproject.toml, uv.lock and uv tree. Which files changed each time?
  4. Lockfile reading. Open uv.lock and find the [[package]] entries for httpx and its dependencies. Identify the version, source, and sdist/wheels+hash fields. Then run uv export --format requirements.txt and compare.
  5. Locked vs frozen. Hand-edit pyproject.toml to add "rich" to dependencies without running uv lock. Run uv sync --locked — paste the error. Run uv lock && uv sync --locked — explain why the second succeeds.
  6. PEP 723 script. Create titles.py outside any project with a # /// script block (requires-python = ">=3.11", dependencies = ["httpx"]) and a main() that fetches one URL. Run uv add --script titles.py rich and inspect the block it writes. Then uv run titles.py. Copy the file into the aitoolkit project and compare uv run titles.py (script metadata wins) with uv run --no-project python titles.py (no project env either) — explain which environment each used.
  7. 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?
  8. venv probe. Create .venv with python3 -m venv, run the venv_probe.py snippet from 2.3 inside and outside, and confirm sys.prefix/sys.base_prefix behave as described.
  9. gitignore audit. In a scratch git repo, write the .gitignore from 7.4, create .env, .env.example, .venv/fake.py, src/x.py, run git add -A && git status --short and git check-ignore -v on each path. Which files got staged?
  10. Layout decision. Convert a flat-layout toy (main.py + mypkg/ at root) to src/ layout. Show that import mypkg fails before uv sync installs it and works after — and explain why that failure is a feature.
  11. Tool vs project dep. Install ruff both ways: uv tool install ruff and uv add --dev ruff. Run which ruff vs uv run ruff --version. Why can both coexist at different versions?
  12. 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 does uv lock --upgrade (no package) risk that --upgrade-package doesn't?
  13. Audit awareness. Run uv audit (preview) or uvx pip-audit against the aitoolkit env. If findings appear, identify whether they're direct or transitive deps and what uv lock --upgrade-package could fix.
Solutions
  1. Default uv init creates .git/, .gitignore, .python-version, pyproject.toml, README.md, src/playground/__init__.py. --bare creates only pyproject.toml (verified in 4.2).
  2. Without --python, requires-python reflects the first interpreter uv finds (e.g. >=3.9); uv add of a >=3.11 package then fails resolution. Set requires-python = ">=3.13" and .python-version to 3.13, then uv add works.
  3. uv add appends to dependencies + re-locks + syncs; --dev writes to [dependency-groups] dev; uv remove deletes from dependencies, uv.lock and .venv — and from a group only when you pass --group/--dev (plain uv remove pytest errors on a dev-only package). uv tree shows the resolved graph.
  4. Each [[package]] has name, version, source = { registry = "https://pypi.org/simple" }, dependencies, sdist/wheels with url+hash, and resolution-markers. uv export renders the same pins as name==version lines plus a header.
  5. uv sync --locked fails: "The lockfile at uv.lock needs to be updated, but --locked was provided." After uv lock, --locked passes because the lock now matches pyproject.toml.
  6. uv add --script titles.py rich appends "rich" to the # /// script block. Outside a project, uv run titles.py uses the script's ephemeral env (httpx + rich). Inside aitoolkit, uv run titles.py still uses the script's env — PEP 723 metadata wins over project deps — while uv run python titles.py uses the project env (script metadata is only read when the .py file is the command), and uv run --no-project python titles.py runs in a bare interpreter env with neither project's nor script's packages guaranteed.
  7. ~=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,<y ranges.
  8. Inside .venv: prefix == base_prefix -> False, prefix ends with .venv -> True; outside: True. The venv layers on the base interpreter.
  9. Staged: .env.example, .gitignore, src/x.py. NOT staged: .env (matched .env*), .venv/fake.py (.venv/), __pycache__ if created. git check-ignore -v prints the matching pattern per path.
  10. After moving the package under src/, import mypkg from the project root fails with ModuleNotFoundError until uv sync installs it — proving tests exercise the installed artefact, not the source tree.
  11. uv tool install ruff puts ruff on PATH globally (isolated); uv add --dev ruff pins it in the project env. which ruff → tool env; uv run ruff → project env. They coexist because they live in different environments.
  12. --dry-run shows candidate changes without writing. --upgrade re-resolves everything the specifiers allow (a breaking transitive bump can sneak in); --upgrade-package moves only the named package and what it forces.
  13. uv audit reports known vulnerabilities in the locked env; check whether each is direct (dependencies) or transitive (uv tree reveals the parent), then uv 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-apis folder (--bare variant, uv add of 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 the aitoolkit skeleton 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 --locked is the exact command their workflows use.
  • 12.7 — dependency pinning, lockfile hashes and uv audit/pip-audit are 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#

  1. What are the three root causes of "works on my machine"?
  2. What does sys.base_prefix point to inside a virtual environment, and what does that tell you about how venvs work?
  3. Which uv init flag creates only pyproject.toml, and when would you choose it?
  4. What's the difference between requires-python and .python-version?
  5. uv add httpx (no version) writes what to pyproject.toml — and is that what an application wants?
  6. Why is uv.lock committed but .venv not?
  7. uv sync --locked vs uv sync --frozen: which verifies the lock is fresh, and which just installs it?
  8. What does uv run do before executing your command, and why does that make activation unnecessary?
  9. Write the PEP 723 header for a script needing httpx on Python ≥3.11.
  10. ~=9.1.4 allows which versions?
  11. Why does a library declare loose specifiers while an application pins exactly?
  12. What's the difference between a dependency group and an extra?
  13. Name two ways uv can run a CLI tool without installing it into your project.
  14. Why does src/ layout prevent "tests pass against uninstalled code"?
  15. Which single CI command catches a stale uv.lock?

Further resources#


← Module 01A: Python Essentials | Module 01B overview | 01B.2 — Environment Variables, Configuration and Secrets →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close