Skip to content

Latest commit

 

History

History
186 lines (127 loc) · 11.9 KB

04_uv.md

File metadata and controls

186 lines (127 loc) · 11.9 KB

UV — Python package manager

Section 4 / 9 · ~15 min · applies to: all participants

Installs: uv into ~/.local/bin/, Python 3.11 into UV's cache, the requests library into the playground's .venv/ · Creates: pyproject.toml, .python-version, main.py, README.md, uv.lock and .venv/ inside the playground · Needs: the playground folder from §1 (§2 on Windows)

UV is the tool we'll use to manage Python projects: installing libraries, isolating environments, and installing Python itself. That is why UV comes before Python in this workshop: the Python you use from §5 on is the one UV installs here.

What is it?

A package manager installs and updates external libraries (other people's code) into your project. Python's traditional answer is pip. UV, built by Astral, does the same job — plus virtual environments, lockfiles, and Python installations themselves — in a single fast tool.

In this workshop we'll use UV for four things:

  1. Installing a project-local Python 3.11 (without touching your system Python).
  2. Creating an isolated environment so installing one library doesn't break another project.
  3. Installing libraries (Jupyter, an HTTP client, an AI library, …).
  4. Recording exact dependency versions in a lockfile so anyone else can reproduce your setup.

Why do we use it?

Python's packaging story has been famously messy. Several tools each solve a slice of it:

Tool What it does Why we don't use it here
pip installs packages no env management, no lockfile, slow on big installs
virtualenv / venv creates isolated environments doesn't manage packages or Python versions
conda env + package manager, cross-language heavy, slow, separate package universe; overkill for pure Python
poetry env + packages + lockfile slower than UV, more rigid
UV env + packages + lockfile + Python versions the modern one-tool answer
Background on pip, conda, and UV

pip is the standard Python package installer, included with every Python install. It does one thing — install packages — and does it well enough. The "modern" pip workflow combines pip with venv (a built-in Python module) for environment isolation:

python3 -m venv .venv             # create an isolated environment in .venv/
source .venv/bin/activate         # activate it (your shell now uses .venv's python)
pip install requests              # install a package into the venv
pip freeze > requirements.txt     # save current versions to a text file (not a real lockfile)
deactivate                        # exit the venv

This works, but it has well-known pain points: slow resolver, slow installs, no real lockfile (pip freeze is a snapshot without hashes or platform metadata), and no help with managing Python versions. Modern Linux distros also refuse pip installs into system Python (PEP 668) — pushing you into a venv anyway, at which point UV is doing the same job faster.

Conda comes from a different world. Created in 2012 by Anaconda for the scientific Python community, it's a cross-language package manager: it installs not just Python libraries but also C/C++/R/Fortran libraries, compilers, CUDA, and more, drawn from its own curated channels (defaults, conda-forge, bioconda, …). For projects with heavy native dependencies that can't easily be installed via pip — GIS, bioinformatics, deep-learning stacks before pip wheels caught up — conda has been the right tool.

The trade-offs are real: conda installs are multi-GB, its environment solver is famously slow (mamba/libmamba helps but isn't yet default everywhere), and conda's package universe is parallel to pip's, so mixing them can break in subtle ways. Conda also doesn't read pyproject.toml, the modern Python standard — it uses its own environment.yml. For pure-Python work, conda is overkill; for projects that genuinely need cross-language tooling, conda still has clear advantages.

UV is from 2024, built by Astral (the team behind the Ruff linter). It's written in Rust, ships as a single binary, and is designed to replace pip, virtualenv, pyenv, and pip-tools — all in one. Its resolver is roughly 10–100× faster than pip's, it uses pyproject.toml, it has a real lockfile (uv.lock) with cryptographic hashes, and it can install Python itself from python-build-standalone. The same uv command sets up Python identically on macOS, Linux, WSL, and native Windows. That's why this workshop installs Python through UV, here, before the Python section.

When you might still reach for pip or conda

  • You inherit a project with only requirements.txt. You can run uv pip install -r requirements.txt, but if collaborators all use plain pip, matching their workflow may be simpler.
  • You need CUDA, GDAL, or another heavy non-Python dependency that's painful to install via pip. Conda's conda-forge channel often has prebuilt binaries that "just work."
  • You're following a tutorial that assumes pip. Use pip for that exercise; switch back to UV for your own projects.

For this workshop and most modern Python work, UV is the right default.

Install

Official documentation: https://docs.astral.sh/uv/

macOS / Linux / WSL
curl -LsSf https://astral.sh/uv/install.sh | sh

Restart your shell after the install completes.

Windows (native)

Use WSL — see section 2.

Verify

uv --version

Try it

Remember the ~/aisc/playground/ folder from §1 that we turned into a Git repo in §3? We'll add a Python project to the same folder now.

cd ~/aisc/playground          # back into the same playground folder we used in §3
uv init --python 3.11         # initialise a UV project here, pinned to Python 3.11

The first time you run this, UV downloads Python 3.11 from python-build-standalone. It's cached under ~/.local/share/uv/python/, so future projects pinned to 3.11 reuse the cached download. This Python is invisible to your system python3: it lives in UV's cache and is only used when you go through UV.

uv init adds a few files to the playground folder. Have a look:

ls -A                         # list everything in the folder, including hidden dotfiles

You should see your existing Git contents (.git/, hello.txt) alongside the new UV scaffolding. Here's what uv init just created:

File What it's for
pyproject.toml Project metadata: name, version, dependencies, the required Python version. The standard Python project file.
.python-version The Python version this project pins (3.11). UV reads this when picking a Python for the venv.
main.py An empty hello-world script. Safe to delete or replace.
README.md An empty README template.

The two files you'll typically edit by hand are pyproject.toml (to declare what you want) and your code itself. Everything else is generated and maintained by UV.

Now add a library and run something:

uv add requests           # install 'requests' + record it in pyproject.toml and uv.lock
uv run python --version   # 'python' inside the venv -> the project's pinned 3.11
uv tree                   # show direct + transitive dependencies
uv run python -c "import requests; print(requests.__version__)"   # use the installed library

What just happened:

  • uv init --python 3.11 created the project files and recorded 3.11 in .python-version.
  • uv add requests created a .venv/ (using UV-managed Python 3.11), installed requests, and wrote a uv.lock file pinning the exact version.
  • uv tree shows the dependency tree of the installed packages
  • uv run python … executed Python inside that venv — note that bare python (no version suffix) gives you 3.11 here, even though your system python3 is a different version.

Two more files appeared from uv add:

  • .venv/ — the actual virtual environment, a folder containing the project-local Python 3.11 and every installed package. Don't commit this; it's large and machine-specific, and can always be rebuilt from the lockfile with uv sync.
  • uv.lock — the exact resolved version (with cryptographic hash) of every direct and transitive dependency. Do commit this. It's how someone else can reproduce your environment exactly.

In short: uv add (and uv remove) keep pyproject.toml, uv.lock, and .venv/ aligned as you work. If they drift apart — most commonly after cloning someone else's UV project — uv sync rebuilds .venv/ from the lockfile so all three agree again.

Two ways to run code in the venv

uv run automatically runs your command inside .venv/ — no manual activation needed. UV reads pyproject.toml and .python-version, picks the right Python, and runs the command in that environment. This is different from the traditional pip + venv workflow, where you have to activate the venv first before running anything:

source .venv/bin/activate     # activate the venv (your shell now uses the venv's python)
python --version              # 'python' now points at the venv's 3.11
which python                  # /Users/.../playground/.venv/bin/python
pip list                      # packages installed in the venv
deactivate                    # back to your system python3

You can still do this with UV if you prefer — both styles work side by side. uv run <command> is convenient for one-off commands and scripts, especially in CI or other automation. Activating with source .venv/bin/activate is convenient when you'll be running many commands in the same shell session and don't want to prefix each with uv run. Pick whichever fits the moment.

Why this is cleaner than installing Python globally

Compared to brew install python@3.11 or apt install python3.11, this approach:

  • Doesn't touch your system Python. Your global python3 still does what every tutorial on the web expects.
  • Is reproducible. Anyone who clones a UV project gets the same Python 3.11 build via uv sync.
  • Is identical across operating systems. No brew, no apt, no deadsnakes PPA, no python.org installer. Just uv.

With this workflow, each Python project ends up with its own pinned Python and pinned dependencies, without conflicts between projects.

Common UV commands

Beyond what you've used so far, these are the commands you'll reach for most:

Command What it does
uv init Initialise a new UV project (or add UV to an existing folder).
uv add <package> Add a runtime dependency to pyproject.toml, install it, and update the lockfile.
uv add --dev <package> Add a development-only dependency (e.g., pytest).
uv remove <package> Remove a dependency.
uv sync Make the venv match pyproject.toml / uv.lock exactly — install missing packages, remove extras. The first command you run after cloning a UV project.
uv lock Update uv.lock to the latest compatible versions, without touching the venv.
uv run <command> Run a command inside the project's venv without manually activating it.
uv pip install <package> A pip-compatible escape hatch — rarely needed; prefer uv add.
uv python install 3.11 Install a Python version into UV's managed cache, independent of any project.

Of these, uv sync is the one you'll use most often as a workshop participant. Every time you git clone a Python project that uses UV, running uv sync once rebuilds the venv exactly as the author had it — same Python version, same packages, same versions. We'll see this in action when we clone and run the workshop's chatbot demo in §9.

Going further