UV
Modern manager for Python virtual environments and dependencies.
UV is a lightweight and high-performance tool designed to manage Python virtual environments and project dependencies.
Why Use UV Instead of pip?
- Automatic management: Automatic creation and management of
.venvenvironments - Deterministic sync: Eliminates "works on my machine" problems
- Optimized performance: Built-in cache and offline mode for faster installs
Quick Start
sh
# Initialize a new uv project
uv init --app my-project
# Move into the project
cd my-project
# Add FastAPI as a dependency
uv add fastapi --extra standard
# Run the FastAPI dev server
uv run fastapi devRecommended Workflow
Project Initialization
sh
# Initialize the project
uv init --app my-projectEnvironment Configuration
sh
# Create the environment with Python 3.12
uv venv --python 3.12Best Practices
- Lock your versions: Use
uv lockanduv syncto ensure all team members use the same dependency versions. Always commit theuv.lockfile. - Optimized cache: UV's local cache speeds up repeated installs and enables offline work. The cache is shared across projects.
VS Code With Many Repos: Isolate Environments Properly
If one repo's .venv appears in another repo, it is usually because the same terminal shell is still active. Virtual environment activation is shell state, not repository state.
Why It Happens
source .venv/bin/activateonly affects the current shell process- VS Code terminals are persistent tabs
- If you
cdto another repo in that same tab, the old env remains active
Recommended Setup (Per Repo)
sh
# from each project root
uv venv --python 3.12Create .vscode/settings.json in each Python repo:
json
{
"python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python"
}Notes:
- Set this at repository level, not global user settings
- In multi-root workspaces, keep this setting inside each folder
Daily Workflow
Prefer project commands through uv to avoid cross-repo shell pollution:
sh
uv run python -V
uv run pytestIf you manually activate an env:
sh
source .venv/bin/activate
# ...work...
deactivateQuick checks when switching repos:
sh
echo "$VIRTUAL_ENV"
which pythonOptional: Auto Activate/Deactivate With direnv
Add .envrc in each project:
sh
source .venv/bin/activateThen allow it once per repo:
sh
direnv allow .direnv will load env vars on directory enter and unload them on exit, which is ideal for many repositories.