Behold, My Stuff

[Home] [Writing] [Links] [CV] [Contact]

Setting Up Python with uv

uv is a Python project and package manager developed by Astral, the same company that makes Ruff. I use uv for every Python-related project now and I think it’s a great tool that replaces pyenv, venv, pip, pipx and flit. This guide is a quick setup guide for how to use uv to manage your Python work.

Table of Contents

You want to…

  1. Install uv
  2. Replace pyenv and venv
  3. Replace pip
  4. Replace flit
  5. Replace pipx

Install uv

For macOS and Linux:

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

See the README for more on installation.

Then you can run uv self update to update uv.

Create a Virtual Environment

Replaces pyenv and venv.

If you want to change as little as possible from an existing venv-based setup, do this:

  1. Remove pyenv from your system, if you have it. uv will now manage our Python versions.
  2. Create a new virtual environment with Python 3.12:
uv venv --python 3.12 venv-folder-name

You can use different Python version if you want, like --python 3.13 or --python 3.11.2. This will create a folder venv-folder-name/. Now you can use source venv-folder-name/bin/activate like you would before to activate your virtual environment.

Use uv to Install Packages

Replaces pip.

uv also has a drop-in replacement for pip that has a much better cache policy and much faster package resolver.

Instead of running pip install requests you can run uv pip install requests and everything just works. uv will use the virtual environment in your directory, even if it’s not activated.

Create a Project

Replaces flit.

Rather than make a virtual and uv pip install and uv pip freeze to record package requirements, use uv’s project dependency management to handle it.

In a directory without a virtual environment, create a new project:

uv init --python 3.12 .

This will create a pyproject.toml file and a .venv/ directory. You don’t have to activate this virtual environment. Fill in the different fields like the name and description.

When you want to run a script in your project, use uv run python .... So for instance, in saev, my project for sparse autoencoders for vision, I run uv run python main.py --help to run my main script in a Python interpreter with all the packages I need.

To install requests, run uv add requests. To install pytest, run uv add --dev pytest. uv will update your dependencies in pyproject.toml and check that your environment works whenever you run a command.

Run Tools

Replaces pipx.

[TODO: I’ll get to this next week :)]


[Relevant link] [Source]

Sam Stevens, 2024