Using uv for Python environments (and when it’s better than Conda)
This tutorial is a practical, end-to-end guide to uv—Astral’s ultra-fast Python package & project manager—geared toward research/dev workflows and HPC/Slurm. You’ll learn how to:
- Install uv and manage Python versions
- Create and use virtual environments
- Add/remove/sync dependencies (PyPI, local paths, Git)
- Lock and pin versions for reproducibility
- Interop with
pip/requirements.txt - Run one-off tools with
uvx - Use uv robustly on clusters with Slurm (
sbatch)
Where it helps, I show two styles: project-native (uv add, uv lock, uv sync) and pip-compatible (uv pip ...).
TL;DR: uv vs Conda
Use uv when you want blazing-fast, Python-focused dependency management and reproducible, per-project virtualenvs (lockfiles, syncs) with simple Python versioning—ideal for apps, libraries, CI, and HPC jobs that primarily depend on PyPI wheels. Benchmarks and independent write-ups consistently show large speedups vs. traditional tools. (Astral Docs)
Keep Conda/Mamba when your environment spans non-Python system libraries (MKL/FFTW/GDAL), complex native stacks, or mixed-language ecosystems where Conda’s binary channels shine. You can also mix: use Conda for a base interpreter + system libs, then uv to manage pure-Python deps inside that interpreter.
1) Install uv (macOS/Linux/Windows)
# macOS/Linux (standalone installer)
curl -LsSf https://astral.sh/uv/install.sh | sh
# or:
wget -qO- https://astral.sh/uv/install.sh | shYou can also pin a specific uv version by using a versioned URL. (Astral Docs)
2) Manage Python versions with uv
uv can install and pin Python interpreters for projects:
# Install (or verify) a managed Python
uv python install 3.11
# See where uv keeps managed interpreters
uv python dir
# Tell uv which Python your project wants
echo "3.11" > .python-version
# (For multi-version projects, use .python-versions with one per line.)uv will honor .python-version/.python-versions, and each uv release freezes a known-good set of downloadable Python builds (upgrade uv to see newer Python point releases). (Astral Docs)
HPC note: If your cluster already provides Python modules, you can skip
uv python installand point uv at that interpreter (see §6).
3) Create & use virtual environments
# Create a venv (default: .venv)
uv venv
# Activate if you like the traditional flow:
source .venv/bin/activate # (PowerShell: .venv\Scripts\Activate)uv requires/uses a venv by default and will automatically find it for subsequent commands. You can also skip manual activation and always run inside the project env via uv run (see §5). (Astral Docs)
4) Project workflow (native uv)
4.1 Initialize a project
uv init
# creates pyproject.toml and scaffolds a projectThe native commands:
uv add: add a dependency (writes topyproject.toml, updates lock)uv remove: remove a dependencyuv lock: (re)solve and writeuv.lockuv sync: sync the venv to matchuv.lockuv tree: inspect dependency graph
4.2 Add dependencies (PyPI)
# Add the latest
uv add numpy
# Add with version spec (PEP 508)
uv add "pandas>=2.2,<2.3"
# Add extras
uv add "ray[default]"4.3 Local packages & Git dependencies
# Local path (editable dev install)
uv add -e ./my_local_pkg
# Git (branch / tag / commit)
uv add "git+https://github.com/owner/repo.git@main"4.4 Lock & sync
# (Re)solve the full set and write uv.lock
uv lock
# Make the environment match the lock *exactly*
uv syncFor strict reproducibility in CI/HPC, use --frozen:
# Fail if uv.lock is stale; do not attempt to modify it
uv run --frozen pytest
uv sync --frozen--frozen runs with the lock as-is; --no-sync skips environment updates and just runs with whatever is present. (Astral Docs)
5) Running code & one-off tools
5.1 Run inside your project env (no activate needed)
uv run python -V
uv run python train.py --epochs 5
uv run pytest -quv run ensures the project venv is used even if not “activated.” (Reddit)
5.2 uvx: ephemeral tool runs (like pipx, but faster)
# Run a CLI from PyPI in an ephemeral cached env
uvx ruff check .
uvx black --check src/
uvx pycowsay "hello world!"These tool envs live in uv’s cache and are disposable; clearing the cache nukes them. (Astral Docs)
6) Using uv with an existing Python (Conda/system/HPC)
If you already have a Python you must use (e.g., module load python/3.11 or a Conda env providing CUDA libs), point uv at it:
# Create a venv that uses the current python
which python # e.g., /share/apps/python/3.11/bin/python
uv venv --python $(which python)
# Or run/sync explicitly with a Python path:
uv run --python /share/apps/python/3.11/bin/python python -V
uv sync --python /share/apps/python/3.11/bin/python(uv can also find/interact with arbitrary environments.) (Astral Docs)
7) Pip-compatible workflow (requirements.txt, pip habits)
If you’re migrating incrementally or collaborating with non-uv projects, you can use uv pip subcommands:
# Install from requirements.txt
uv pip install -r requirements.txt
# Freeze current env
uv pip freeze > requirements.txt
# Inspect or clean
uv pip list
uv pip check
uv pip treeYou can also install directly from pyproject.toml with uv pip install -r pyproject.toml (and enable extras with --extra). (Astral Docs)
Tip: For new projects, prefer the native
uv add/sync/lockflow;uv pipexists for interop and familiarity. (Medium)
8) Versioning strategies
8.1 Package versions (PEP 508 specifiers)
Use standard specifiers in uv add or in pyproject.toml:
- Exact:
package==1.4.2 - Ranges:
package>=1.2,<2.0 - Pre-releases:
--preon the command or mark in pyproject
8.2 Python versions
- Keep a
.python-versionin the repo (e.g.,3.11) so collaborators/CI know what to install. uv will install/manage that version automatically if you use managed Pythons. (Astral Docs)
8.3 Lockfiles
- Commit
uv.lockfor deterministic resolution; in CI and HPC useuv sync --frozen(oruv run --frozen …) so jobs fail rather than re-lock when the lock is out of date. (Astral Docs)
9) Caching and performance (HPC-friendly)
uv keeps a global cache to accelerate repeated installs and uvx tool runs. You can relocate it (often useful on clusters):
# See current cache dir
uv cache dir
# One-off run with a custom cache
uv pip install --cache-dir /scratch/$USER/uv-cache -r requirements.txt
# Persistent (e.g., in ~/.bashrc)
export UV_CACHE_DIR=/scratch/$USER/uv-cache10) Slurm (sbatch) recipes
Below are hardened patterns for clusters (login node = internet; compute nodes = maybe not; shared scratch for cache).
10.1 Prepare once on the login node
# On login node, in your project directory:
module load python/3.11 # if your site uses modules
uv venv --python $(which python) # or `uv python install 3.11` if allowed
uv add "numpy>=2,<3" pandas scipy
uv lock # write uv.lock
# (Optional) warm the cache to speed first job:
uv syncCommit pyproject.toml, .python-version (if used), and uv.lock.
10.2 Minimal sbatch script (reproducible & fast)
#!/bin/bash
#SBATCH -J myjob
#SBATCH -A myacct
#SBATCH -p gpu
#SBATCH -N 1
#SBATCH --gpus=1
#SBATCH -t 04:00:00
#SBATCH -o logs/%x.%j.out
#SBATCH -e logs/%x.%j.err
set -euo pipefail
# 1) Pick a cache on local scratch or fast shared storage
export UV_CACHE_DIR="${SCRATCH:-$HOME}/uv-cache"
# 2) Choose Python interpreter:
module load python/3.11 # or skip if using uv-managed Python
PY=$(which python)
# 3) Ensure venv exists and uses that Python
# (idempotent: do nothing if .venv already present)
if [[ ! -d ".venv" ]]; then
uv venv --python "$PY"
fi
# 4) Sync exactly to the lock (no network changes, fail if stale)
uv sync --frozen --python "$PY" --no-progress
# 5) Run your workload inside the env (no activation required)
uv run --python "$PY" --no-sync python -u train.py --epochs 5 --batch 128Notes:
--frozenmakes jobs deterministic (won’t re-lock). (Astral Docs)UV_CACHE_DIRon node-local SSD or$SCRATCHcuts cold-start time. (Astral Docs)uv run --no-syncassumesuv syncjust ran, avoiding redundant checks. (Astral Docs)
10.3 Network-restricted compute nodes
If compute nodes can’t access the internet:
- Resolve & download on the login node (
uv lock+uv syncto warm cache). - Ensure
$UV_CACHE_DIRis on a shared filesystem visible to compute nodes (or stage wheels to a per-job cache that you rsync).
You can also use--no-index/--find-linksworkflows for fully offline mirrors, but behavior nuances mirror pip’s semantics. (GitHub)
10.4 Multi-job pipelines
- Add
uv sync --frozenat the top of each job. If the lock changes, only the job where it changed will re-sync. - Use
uvxfor ephemeral tools in jobs (e.g.,uvx ruff,uvx pytest)—fast and doesn’t pollute project envs. (Astral Docs)
11) Examples
11.1 Minimal pyproject.toml (library)
[project]
name = "my-lib"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"numpy>=2,<3",
"scipy>=1.14,<1.15",
"pandas>=2.1,<2.3",
]
[tool.uv] # optional uv settings
# environments = ["cp311-manylinux_x86_64"] # narrow resolution targets if desired(Advanced settings let you restrict resolution environments to speed locks / avoid unsatisfiable branches.) (Astral Docs)
11.2 Local dev + tests
uv add -e .[dev,test] # editable install with extras
uv run pytest -q
uv run ruff check .11.3 Pip-style project
uv venv
uv pip install -r requirements.txt
uv pip freeze > requirements.txt
uv pip check
uv pip tree12) Tips & gotchas
- Speed: uv is written in Rust and aggressively caches/parallelizes; independent articles report large speedups over pip/poetry in real projects. (Real Python)
uvxvs project deps: Keep lint/format/test CLIs out of your core env by running them viauvx; your runtime remains minimal. (Astral Docs)- Cache hygiene: If disk is tight on a shared machine:
uv cache prune/uv cache clean. (Seeuv cachesubcommands.) (Astral Docs) - Managed Python availability: uv’s list of downloadable Pythons is frozen per uv release; update uv to see the newest Python patch/minor releases. (Astral Docs)
- Interop mindset: Prefer native
uv add/sync/lockfor modern projects; useuv pipfor compatibility bridges. (Medium)
13) Cheat sheet
# Python
uv python install 3.11
echo "3.11" > .python-version
# Env
uv venv # create .venv
source .venv/bin/activate # optional
# Dependencies (native)
uv add "numpy>=2,<3"
uv remove numpy
uv lock
uv sync # match env to uv.lock
uv run python script.py
# Pip interop
uv pip install -r requirements.txt
uv pip freeze > requirements.txt
uv pip list | uv pip check | uv pip tree
# Tools
uvx ruff check .
uvx black src/
uvx pycowsay "moo"
# Cache
uv cache dir
UV_CACHE_DIR=/scratch/$USER/uv-cache uv sync14) Is uv “better than Conda”?
For Python-centric workflows: often yes—faster env creation/installs, deterministic uv.lock, single-file project config, drop-in tool runner (uvx), simple Python versioning, and smooth CI/HPC stories. (Astral Docs)
For heavy native stacks or cross-language ecosystems: Conda/Mamba still wins at distributing curated binaries and system libs. A pragmatic hybrid is common on clusters: Conda for base interpreter + CUDA/system libs, uv for day-to-day Python deps in a project venv.
Further reading
- Official uv docs (features, commands, Python/version management, tools, cache): (Astral Docs)
- Installing uv: (Astral Docs)
- Pip-compatible commands: (Astral Docs)
- Speed/benchmarks & tutorials: (Real Python)