uv Tutorial:Quickly Get Started with the Next-Gen Python Toolchain
uv, a high-performance Python manager in Rust. This tutorial guides installation, configuration, and demonstrates core commands for version management, dependency handling, environment activation, and script execution.
Foreword
The Python ecosystem is constantly evolving, and so are the tools that help developers efficiently manage their projects. This article will take an in-depth look at uv
, an innovative tool появившийся from Astral (the creators of the Ruff linter), designed to revolutionize Python package and environment management. For developers seeking an efficient, integrated alternative to some functionalities of pip
, venv
, virtualenv
, pip-tools
, and even pyenv
, uv
is worth considering.
uv
is written in Rust, and one of its core design goals is extreme speed. However, speed is not its only highlight. uv
aims to provide a comprehensive, unified solution for many common Python development tasks.
Core Design Philosophy of uv
- Extreme Performance: The use of Rust allows
uv
to exhibit remarkable speed in operations such as dependency resolution, package downloading, and installation, significantly outperforming existing Python tools. - Unified Experience:
uv
integrates functionalities like Python version management, project initialization, dependency management, script execution, tool running, and package building and publishing into a single command-line interface, reducing the overhead of switching between tools. - Modern Python Practices: It emphasizes project configuration via
pyproject.toml
and introduces a robust, cross-platformuv.lock
lock file mechanism. - Backward Compatibility (with caveats): The
uv pip
subcommand offers an interface highly compatible with commonpip
andpip-tools
workflows, facilitating user migration, though it's not intended to be an exact clone ofpip
.
Installing and Configuring uv
Before diving into its features, let's first cover how to install and configure uv
.
Installing uv
uv
offers multiple installation methods to suit different operating systems and preferences.
-
Standalone Installation Script (Recommended): This is the most direct and cross-platform consistent installation method.
- macOS and Linux: Open your terminal and run either of the following commands:
# Using curl curl -LsSf https://astral.sh/uv/install.sh | sh # Or, if curl is not available on your system, use wget # wget -qO- https://astral.sh/uv/install.sh | sh
To install a specific version (e.g., 0.7.5):
curl -LsSf https://astral.sh/uv/0.7.5/install.sh | sh
- Windows (PowerShell): Open PowerShell and run:
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
To install a specific version (e.g., 0.7.5):
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/0.7.5/install.ps1 | iex"
By default,
uv
is installed to the user'sbin
directory (e.g.,~/.local/bin
), and the installation script usually tries to add this directory to yourPATH
automatically. You can customize the installation path by setting theUV_INSTALL_DIR
environment variable, or prevent the script from modifying shell configuration files withINSTALLER_NO_MODIFY_PATH=1
. -
Via PyPI (using
pipx
orpip
): It's recommended to installuv
into an isolated environment usingpipx
:pipx install uv
Alternatively, use
pip
(not recommended for global installation):pip install uv
Note: If a pre-compiled wheel is not available for your platform,
pip
will attempt to builduv
from source, which requires a Rust toolchain. -
Other Package Managers:
- Homebrew (macOS):
brew install uv
- WinGet (Windows):
winget install --id=astral-sh.uv -e
- Scoop (Windows):
scoop install main/uv
- Cargo (requires Rust environment):
cargo install --git https://github.com/astral-sh/uv uv
-
Docker Images:
uv
provides official Docker images, e.g.,ghcr.io/astral-sh/uv:latest
or specific versions likeghcr.io/astral-sh/uv:0.7.5
.
After installation, verify it by running uv --version
or uv self version
.
Updating uv
- If installed via the standalone script:
uv self update # uv self update <version> # To update to a specific version
- If installed via other package managers, use their respective update commands (e.g.,
pipx upgrade uv
).
Shell Autocompletion
Enabling shell autocompletion for uv
and uvx
commands can significantly improve efficiency. For example, for Bash:
echo 'eval "$(uv generate-shell-completion bash)"' >> ~/.bashrc
echo 'eval "$(uvx --generate-shell-completion bash)"' >> ~/.bashrc
# For Zsh, Fish, PowerShell, etc., refer to the official documentation for the corresponding commands
After completing these steps, restart your shell or reload the configuration file.
Configuring uv
uv
's behavior can be configured in several ways, with the following order of precedence (highest to lowest):
- Command-line arguments.
- Environment variables: Prefixed with
UV_
, e.g.,UV_INDEX_URL
. - Project-level configuration files:
- The
[tool.uv]
table in thepyproject.toml
file in the project root. - A
uv.toml
file in the project root (takes precedence over[tool.uv]
inpyproject.toml
if both exist in the same directory).
- The
- User-level configuration file: e.g.,
~/.config/uv/uv.toml
(Linux/macOS). - System-level configuration file: e.g.,
/etc/uv/uv.toml
.
User-level and system-level configurations must use the uv.toml
format. Configurations are merged, with project-level taking precedence over user-level, and user-level over system-level.
- Disable configuration discovery: Use the
--no-config
command-line argument. - Specify a particular configuration file: Use
--config-file /path/to/my-uv.toml
. .env
file loading (foruv run
):uv run
can load environment variables from.env
files via--env-file
orUV_ENV_FILE
.
In-depth Look at uv
's Core Features
1. Python Version Management (uv python ...
)
uv
's management of Python interpreters themselves is a standout feature.
- Managed vs. System Python:
uv
can discover and use existing Python installations on the system ("system Python"). It can also download and install Python versions itself ("managed Python"). - Python Distribution Sources:
uv
relies on Astral'spython-build-standalone
project for pre-compiled CPython binaries and fetches PyPy from its official project. - On-demand Installation and Version Requesting: The
--python
flag allows requesting specific Python versions in mostuv
commands. Supported formats are very flexible. If a requested version is not available locally,uv
will download and install it by default. .python-version
File Integration:uv
supports.python-version
files for declaring default Python versions for projects or globally. Theuv python pin
command easily creates these files.uv python pin 3.12 # Creates .python-version in the current directory uv python pin --global 3.11 # Creates a global .python-version file
- Executable Installation (Preview):
uv python install 3.12 --preview
can install executables likepython3.12
into the user's path.
2. Project and Workspace Management
uv
's project management centers around pyproject.toml
and introduces the concept of Workspaces.
- Project Initialization (
uv init
): Quickly creates new projects adhering to modern Python project structures.uv init my_app # Creates an application project uv init --lib my_library # Creates a library project
- Dependency Declaration: Declared in
pyproject.toml
's[project.dependencies]
,[project.optional-dependencies]
(extras), and[dependency-groups]
(PEP 735, e.g.,dev
group).[tool.uv.sources]
allows specifying alternative sources for specific dependencies.uv add requests uv add --dev pytest
uv.lock
– Universal Lock File:uv lock
generatesuv.lock
, a cross-platform lock file recording exact resolved dependency versions for all environments.- Automatic Locking and Syncing:
uv run
anduv sync
commands automatically check and updateuv.lock
and the.venv
virtual environment before execution.uv sync uv lock --upgrade # Upgrades all packages and updates the lock file
- Workspaces (
[tool.uv.workspace]
): Allows managing multiple related Python packages as a single unit, sharing a singleuv.lock
.
3. Script Execution (uv run
)
- PEP 723 Inline Metadata: For standalone Python scripts,
uv run
supports declaring dependencies and Python version requirements directly in the script file header using special comment blocks.
Use# /// script # requires-python = ">=3.10" # dependencies = ["requests"] # /// import requests # ...
uv add --script my_script.py requests
to automatically add metadata. - Ephemeral Environments: When running scripts with inline metadata,
uv
automatically creates a temporary, isolated environment. - Shebang Support:
#!/usr/bin/env -S uv run --script
.
4. Tool Execution and Installation (uvx
, uv tool ...
)
uvx <tool_name>
: Executes tools in a temporary, isolated environment without permanent installation.uvx ruff check .
uv tool install <package_name>
: Installs tools into the user'sbin
directory, making them globally available.uv tool install black ruff
- Version and Source Control:
uvx ruff@0.3.0
oruvx --from 'ruff==0.3.0'
.
5. pip
-Compatible Interface (uv pip ...
)
Provided for users accustomed to pip
workflows.
-
Environment Creation (
uv venv
):uv venv .venv --python 3.11
-
Environment Activation (
uv venv
):Virtual environments created by
uv
(e.g.,.venv
) are standard and thus activated the same way as those created byvenv
orvirtualenv
.- macOS/Linux (Bash/Zsh):
source .venv/bin/activate
- Windows (PowerShell):
.\.venv\Scripts\Activate.ps1
- Windows (cmd.exe):
.\.venv\Scripts\activate.bat
After activation, the shell prompt will change, and subsequent
python
andpip
commands will operate within this environment. Usedeactivate
to exit.Note: Many
uv
commands (likeuv run
,uv sync
) automatically detect and use.venv
without manual activation. - macOS/Linux (Bash/Zsh):
-
Package Installation and Uninstallation:
# Assuming .venv is activated uv pip install django uv pip uninstall django
-
Dependency Compilation (
uv pip compile
):uv pip compile requirements.in -o requirements.txt
-
Environment Syncing (
uv pip sync
):uv pip sync requirements.txt # Accurately syncs the environment
6. Efficient Dependency Resolution and Caching
- PubGrub Resolver:
uv
usespubgrub-rs
for dependency resolution. - Universal Resolution:
uv lock
performs universal resolution by default, creating auv.lock
that considers all platforms and Python versions. - Aggressive Caching: Caches downloaded wheels, built sdists, Git clones, etc.
uv cache dir # View cache directory uv cache clean # Clean all cache uv cache prune --ci # Optimize cache for CI
7. Building and Publishing
uv build
: Calls the project-defined build backend to build sdists and wheels.uv build # Builds sdist and wheel to dist/
uv publish
: Uploads built distributions to a package index.uv publish dist/*
More
For more information and advanced usage of uv
, please refer to the official uv
documentation.