uv instead of venv/pip

Python
packaging
Published

August 31, 2024

uv recently released its 0.3 version.

uv is a package and project manager that potentially allows me to fully replace my venv/pip/pip-tools workflow and the use of pyenv as well as pipx. It provides a single tool, is significantly faster, and includes a complete project manager.

The 0.3 release added many new features and comprehensive documentation. Version 0.4, which revised the project workflow, has been released.

Package management has been challenging in Python and has often taken me a lot of time. uv has the potential to harmonize the approaches and tools I have used with a single tool.

Here are the uv commands relevant to me, a collection inspired by this post.

Installation

It is recommended to install uv globally instead of using pip install uv.

uv workflow

Specify Python dependencies in a pyproject.toml (see Projects below).

uv add ruff

uv run ruff check

uv lock --upgrade
uv sync

source .venv/bin/activate
which python

Projects

Create a project with a README.md, a pyproject.toml, and an example script.

uv init
uv run hello.py

You can also specify a project name to create the project in a new folder.

Python versions

uv can install a specific Python version from python-build-standalone.

The Python version in a pyproject.toml or a .python-version file is used.

This allows me to replace pyenv, which I have used to manage different Python versions.

uv venv --python 3.11

uv python list
uv python install --reinstall 3.10 3.11

There may be minor differences with other Python builds.

Scripts

You can specify dependencies as embedded metadata in a script. uv will run the script and install the dependencies.

echo 'import urllib3; print(urllib3.request("GET", "http://httpbin.org/robots.txt").data)' > robots.py

uv add --script robots.py urllib3

uv run robots.py

Python tools

You can run and install Python tools with uvx.

It can be used as a replacement for pipx.

uvx ruff clean

uv tool install ruff
ls -l $(which ruff)

uv tool list
uv tool upgrade --all

venv/pip workflow

My goal is to use the uv workflow, but here are some examples of using uv as as venv/pip/pip-tools replacement with the respective parameters.

uv venv
uv pip install urllib3
source .venv/bin/activate
which python

echo "urllib3" > requirements.in
uv pip compile -U requirements.in -o requirements.txt
uv pip sync requirements.txt

Clean-up

The uv cache folder can get large quickly, so it is helpful to clean it up regularly

uv cache prune

uv cache clean

du -h -d 1 $(uv cache dir)

Keep in mind that many .venv folders are created with a uv workflow, so you may want to remove them at some point.

find . -type d -name ".venv" -print0 | xargs -0 du -sh