←Back to Guides
๐ŸPython & Toolingโฑ๏ธ 15 min read•Updated October 2026

Astral uv & Modern Python Tooling Master Cheat Sheet

A definitive production CLI cheat sheet and transition runbook for Astral uv, the ultra-fast Rust-powered Python package manager. Master instant virtual environments, universal cross-platform lockfiles (uv.lock), automated multi-version Python runtime management, and high-speed Docker layer caching.

#Python#uv#Astral#pip#virtualenv#pyproject.toml#DevOps#Docker#Performance

1. The Rust Revolution in Python: uv Architecture & Performance Advantages

For decades, the Python developer experience has been fragmented across disjointed utilities: pip for package installation, virtualenv for environments, pyenv for Python interpreter versions, pipx for standalone CLI applications, and poetry or pip-tools for dependency resolution and lockfiles. Astral's uv consolidates all of these responsibilities into a single, cohesive binary written in Rust. By utilizing copy-on-write (reflinks) on modern filesystems, parallel PubGrub SAT dependency resolution, global wheel caching, and optimized HTTP/2 network transport, uv executes dependency installations and environment creations 10x to 100x faster than legacy tooling. The following table summarizes how uv unifies the Python ecosystem:
Installing uv Across Linux, macOS, and Windows
# Standalone installer for Linux and macOS (No Python dependency required)
curl -LsSf https://astral.sh/uv/install.sh | sh

# Standalone installer for Windows (PowerShell)
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

# Alternatively, install via Homebrew on macOS
brew install uv

# Verify installation and active Rust engine version
uv --version

Installs the self-contained uv binary without requiring an existing Python runtime.

Legacy ToolAstral uv SuccessorPerformance MultiplierConsolidated FeatureCopy
pip installuv pip install / uv add10x - 100x fasterParallel wheel downloading, SAT-solving, and global symlink/reflink cache
python -m venvuv venv80x faster (~0.01s)Instant virtual environment provisioning using filesystem reflinks
pyenv installuv python installNative cross-platformDownloads standalone pre-built CPython and PyPy runtimes automatically
pipx runuvx / uv tool runZero-latency ephemeral cacheExecutes any PyPI CLI tool without permanent global installation
pip-compile / poetryuv lock / uv syncNear-instant resolutionGenerates cross-platform deterministic universal uv.lock files

2. Virtual Environments & uv pip Drop-In Compatibility

For teams maintaining existing legacy codebases that rely on standard requirements.txt files, uv provides a fully drop-in compatible sub-interface: uv pip. This allows immediate 10x-100x acceleration without changing deployment scripts, Dockerfiles, or CI/CD pipelines. Key capabilities: - uv venv creates a complete, activated virtual environment in approximately 10 milliseconds. - uv pip compile parses loose requirements.in declarations and solves an exact, hash-pinned requirements.txt manifest in fractions of a second. - uv pip sync synchronizes your environment to match requirements.txt exactly, automatically uninstalling untracked orphaned packages.
Accelerating Standard pip Workflows with uv
# 1. Create a modern virtual environment with Python 3.12 in ~12 milliseconds
uv venv --python 3.12 .venv

# 2. Activate the virtual environment (Standard command)
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# 3. Fast installation of complex multi-gigabyte data science wheels
uv pip install fastapi uvicorn "pydantic>=2.0" torch

# 4. Compile unpinned requirements.in into an exact deterministic lockfile
uv pip compile requirements.in -o requirements.txt

# 5. Strict synchronization: uninstalls any extra package not in requirements.txt
uv pip sync requirements.txt

Replaces legacy virtualenv and pip commands with drop-in, multi-threaded Rust equivalents.

TaskLegacy CommandModern uv EquivalentOperational BenefitCopy
Create venvpython3 -m venv .venvuv venvCreates environment in ~0.01s via hardlinks/reflinks
Install packagespip install -r reqs.txtuv pip install -r reqs.txtParallel HTTP/2 wheel downloads with global deduplication
Compile lockfilepip-compile requirements.inuv pip compile requirements.inResolves SAT constraints across thousands of packages in under 1 second
Prune orphaned depspip-sync requirements.txtuv pip sync requirements.txtGuarantees identical environment across staging and production
List treepip listuv pip treeVisualizes complete dependency graph and nested transitive requirements

3. Automated Python Runtime Management (No pyenv Required)

Managing multiple installed Python interpreter versions across development machines has historically required external utilities like pyenv, alongside complex C-compiler toolchains to build Python from source. uv introduces native, first-class Python runtime management: - uv automatically downloads and manages pre-built, optimized standalone CPython and PyPy binaries directly from the official Python Software Foundation. - It automatically detects project requirements from .python-version files or requires-python fields in pyproject.toml. - If a project requires Python 3.11 and you only have Python 3.13 installed, running uv run or uv venv will silently download and use Python 3.11 on demand without user intervention.
Managing CPython and PyPy Interpreters with uv
# List all available Python interpreters (Local and Remote)
uv python list

# Download and install specific CPython versions
uv python install 3.11 3.12 3.13

# Install PyPy for high-throughput JIT workloads
uv python install pypy@3.10

# Pin the current repository to a specific Python version (Creates .python-version)
uv python pin 3.12

# Run an ad-hoc command against an explicit Python version without installing it globally
uv run --python 3.10 -c "import sys; print(sys.version)"

Installs and switches Python interpreter versions instantly without compiling from source.

uv CommandTarget ScopeResolution MechanismPractical ExampleCopy
uv python install <ver>Global SystemDownloads pre-compiled standalone CPython releaseuv python install 3.13
uv python listInspectionDisplays installed, active, and downloadable interpretersuv python list --all
uv python pin <ver>Project DirectoryWrites .python-version file locking project interpreteruv python pin 3.12
uv python findEnvironmentPrints exact filesystem path to currently resolved Python binaryuv python find 3.11
uv python uninstall <ver>Global StorageRemoves cached interpreter to reclaim disk storageuv python uninstall 3.9

4. Modern Project Lifecycle: pyproject.toml, uv lock & uv sync

For new modern Python projects, uv provides a complete declarative workflow centered around pyproject.toml (PEP 517 / 518 / 621) and a universal uv.lock file. Unlike traditional lockfiles that are platform-dependent (requiring separate locks for macOS ARM64 and Linux x86_64), uv.lock is universal: - A single uv.lock resolves all dependency combinations across operating systems, architectures, and Python versions simultaneously. - uv add and uv remove automatically update both pyproject.toml and uv.lock. - uv run executes scripts within the project environment automatically, ensuring you never forget to activate your virtualenv.
Initializing and Managing a Modern uv Project
# 1. Initialize a new modern Python application project
uv init my-service
cd my-service

# 2. Add dependencies (Updates pyproject.toml and resolves uv.lock automatically)
uv add fastapi "uvicorn[standard]" httpx

# 3. Add development-only dependencies (e.g. testing and linting tools)
uv add --dev pytest ruff mypy

# 4. Execute application inside the synchronized virtualenv (Zero manual activation)
uv run uvicorn main:app --reload

# 5. In CI/CD pipelines: install exact dependencies strictly matching lockfile
uv sync --frozen --no-dev

Full project lifecycle workflow from initialization and dependency addition to CI lockfile enforcement.

uv Project CommandTarget FileOperational ActionProduction Best PracticeCopy
uv initpyproject.tomlScaffolds clean PEP 621 project templateUse --app for services or --lib for reusable packages
uv add <pkg>pyproject.toml + uv.lockResolves dependency, updates lockfile, installs wheelSpecify semver ranges (e.g. "pydantic>=2.5")
uv add --dev <pkg>pyproject.toml [dev]Adds package to separate development dependency groupKeep test and lint tooling out of production images
uv remove <pkg>pyproject.toml + uv.lockUninstalls package and purges unused transitive dependenciesPrevents dependency bloat across project milestones
uv sync --frozenEnvironment SyncInstalls lockfile without checking for remote updatesMandatory flag in production Dockerfiles and CI runners
uv lock --upgradeuv.lockRe-evaluates latest compatible package versions from PyPIRun regularly to ingest security patches and bug fixes

5. Standalone Tools (uvx), Ephemeral Scripts & Multi-Stage Docker Caching

Two of uv's most powerful capabilities are ephemeral script execution and ultra-fast container builds. Ephemeral Scripts & Inline Metadata (PEP 723): With uv, a single standalone Python script can declare its own dependencies inside an inline comment block. Running uv run script.py will automatically provision a temporary isolated environment, install the dependencies, execute the script, and clean up. Standalone CLI Tools (uvx): The uvx command (shorthand for uv tool run) executes any tool from PyPI (such as Ruff, Black, HTTPie, or yt-dlp) in an isolated ephemeral sandbox without polluting your global system packages. High-Speed Multi-Stage Docker Builds: By leveraging uv's standalone binary and BuildKit cache mounts (--mount=type=cache,target=/root/.cache/uv), container build times can drop from minutes to sub-second cached rebuilds.
Executing a Standalone Script with Inline Dependency Metadata (PEP 723)
# Save the following as 'scrape.py':
cat << 'EOF' > scrape.py
# /// script
# requires-python = ">=3.11"
# dependencies = [
#   "requests",
#   "beautifulsoup4",
# ]
# ///

import requests
from bs4 import BeautifulSoup

resp = requests.get("https://example.com")
soup = BeautifulSoup(resp.text, "html.parser")
print("Page Title:", soup.title.string)
EOF

# Execute script with automatic on-the-fly dependency provisioning:
uv run scrape.py

Executes standalone scripts declaring self-contained dependencies via PEP 723 metadata.

Ultra-Fast Multi-Stage Production Dockerfile with uv Cache Mounts
# syntax=docker/dockerfile:1
FROM python:3.12-slim-bookworm AS builder

# Install uv from official standalone image
COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv

WORKDIR /app

# Enable bytecode compilation and use system environment in container
ENV UV_COMPILE_BYTECODE=1 \
    UV_LINK_MODE=copy

# 1. Cache dependency installation separately from application code
COPY pyproject.toml uv.lock ./
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --frozen --no-install-project --no-dev

# 2. Copy application source and finalize sync
COPY . .
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --frozen --no-dev

# Final production stage
FROM python:3.12-slim-bookworm

WORKDIR /app
COPY --from=builder /app /app
ENV PATH="/app/.venv/bin:$PATH"

EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Production Dockerfile achieving sub-second cached rebuilds using uv BuildKit cache mounts.

Feature / TaskCommand SyntaxExecution SandboxKey Operational BenefitCopy
Run ephemeral tooluvx ruff check .Isolated temporary cacheNever pollutes system environment; always uses latest version
Install persistent tooluv tool install ruffDedicated isolated venv in ~/.localExposes binary directly on $PATH like pipx
Self-contained scriptuv run script.pyOn-the-fly ephemeral venvReads inline PEP 723 metadata; fully portable across machines
Compile bytecodeUV_COMPILE_BYTECODE=1Build-time flagPre-compiles .pyc files for faster container cold-start boot times

๐ŸŽ“Explore More Guides

โœจ