UV: Modern Python Package Manager That's 10-100x Faster

# UV: Package Manager Python Modern yang 10-100x Lebih Cepat Mengelola dependensi Python selalu menjadi tantangan tersendiri. Kita perlu menginstal pip, virtualenv, pyenv, dan poetry secara terpisah,...

By Ruby Abdullah · · tutorial
UVPythonPackage ManagerVirtual EnvironmentDevOps

UV: Modern Python Package Manager That's 10-100x Faster

Managing Python dependencies has always been a challenge. We need to install pip, virtualenv, pyenv, and poetry separately, then configure each tool individually. UV arrives as an all-in-one solution that replaces all these tools with 10-100x faster performance. Written in Rust by the Astral team (creators of Ruff), UV is a next-generation Python package manager that transforms how we work with the Python ecosystem.

In this tutorial, we will learn UV comprehensively from installation, project management, virtual environments, to a practical example of building an ML project from scratch.

Why UV?

Before diving into the technical details, let's understand why UV is worth considering:

  • Exceptional speed: 10-100x faster than pip thanks to Rust implementation and global caching
  • All-in-one: Replaces pip, pip-tools, virtualenv, pyenv, and poetry in a single binary
  • Built-in lockfile: Reproducible builds without additional configuration
  • Python version management: Install and switch Python versions without pyenv
  • Cross-platform: Works consistently on Linux, macOS, and Windows
  • Drop-in replacement: Compatible with the existing pip ecosystem

Installing UV

Linux and macOS

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

Windows (PowerShell)

powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

Using pip (alternative)

pip install uv

Using Homebrew (macOS)

brew install uv

Verify the installation:

uv --version

Updating UV

uv self update

Creating Projects with uv init

UV provides an easy way to start new Python projects:

uv init my-project

cd my-project

This command creates the following project structure:

my-project/

├── .python-version

├── README.md

├── hello.py

└── pyproject.toml

The generated pyproject.toml:

[project]

name = "my-project"

version = "0.1.0"

description = "Add your description here"

readme = "README.md"

requires-python = ">=3.12"

dependencies = []

Initialization Options

# Create project as a library (with src layout)

uv init --lib my-library

Create project as an application

uv init --app my-app

Specify minimum Python version

uv init --python 3.11 my-project

Create project in current directory

uv init

For library projects, the structure will be different:

my-library/

├── .python-version

├── README.md

├── pyproject.toml

└── src/

└── mylibrary/

├── init.py

└── py.typed

Dependency Management

Adding Dependencies

# Add a package

uv add requests

Add with specific version constraints

uv add "pandas>=2.0,<3.0"

Add multiple packages at once

uv add numpy scikit-learn matplotlib

Add development dependency

uv add --dev pytest ruff mypy

Add optional dependency group

uv add --group docs sphinx sphinx-rtd-theme

Each time you run uv add, UV will automatically:

  • Add the package to pyproject.toml
  • Resolve the entire dependency tree
  • Update uv.lock
  • Install the package into the virtual environment
  • Removing Dependencies

    # Remove a package
    

    uv remove requests

    Remove a dev dependency

    uv remove --dev mypy

    Viewing the Dependency Tree

    uv tree
    

    Example output:

    my-project v0.1.0
    

    ├── numpy v1.26.4

    ├── pandas v2.2.1

    │ ├── numpy v1.26.4

    │ ├── python-dateutil v2.9.0

    │ │ └── six v1.16.0

    │ ├── pytz v2024.1

    │ └── tzdata v2024.1

    └── scikit-learn v1.4.1

    ├── joblib v1.3.2

    ├── numpy v1.26.4

    ├── scipy v1.12.0

    │ └── numpy v1.26.4

    └── threadpoolctl v3.3.0

    Syncing Dependencies

    # Install all dependencies from lockfile
    

    uv sync

    Install including dev dependencies

    uv sync --dev

    Install without dev dependencies (for production)

    uv sync --no-dev

    Install specific group

    uv sync --group docs

    Virtual Environments with uv venv

    Creating a Virtual Environment

    # Create default venv (.venv)
    

    uv venv

    Create with custom name

    uv venv my-env

    Create with specific Python version

    uv venv --python 3.11

    Create with seed packages (pip, setuptools)

    uv venv --seed

    Activating the Virtual Environment

    # Linux/macOS
    

    source .venv/bin/activate

    Windows (PowerShell)

    .venv\Scripts\Activate.ps1

    Windows (CMD)

    .venv\Scripts\activate.bat

    Using uv pip (Compatibility Mode)

    UV also provides a pip-compatible interface:

    # Install a package
    

    uv pip install requests

    Install from requirements.txt

    uv pip install -r requirements.txt

    Freeze dependencies

    uv pip freeze

    Compile requirements

    uv pip compile requirements.in -o requirements.txt

    Uninstall

    uv pip uninstall requests

    Lockfile (uv.lock)

    UV automatically creates and manages the uv.lock file containing exact versions of all dependencies. This file ensures reproducible builds across all environments.

    # Generate/update lockfile
    

    uv lock

    Update specific package in lockfile

    uv lock --upgrade-package requests

    Update all packages

    uv lock --upgrade

    The uv.lock file should be committed to version control (git) to ensure all developers and CI/CD pipelines use the same versions.

    Example uv.lock

    version = 1
    

    requires-python = ">=3.12"

    [[package]]

    name = "numpy"

    version = "1.26.4"

    source = { registry = "https://pypi.org/simple" }

    sdist = { url = "...", hash = "sha256:..." }

    wheels = [

    { url = "...", hash = "sha256:..." },

    ]

    Running Scripts with uv run

    uv run allows you to execute commands in the project context without manually activating the virtual environment:
    # Run a Python script
    

    uv run python main.py

    Run pytest

    uv run pytest

    Run a module

    uv run python -m flask run

    Run with inline dependencies

    uv run --with rich python -c "from rich import print; print('[bold green]Hello UV![/]')"

    Inline Script Dependencies

    UV supports PEP 723 inline script metadata. You can define dependencies directly inside Python files:

    # /// script
    

    requires-python = ">=3.12"

    dependencies = [

    "requests",

    "rich",

    ]

    ///

    import requests

    from rich import print

    response = requests.get("https://api.github.com/repos/astral-sh/uv")

    data = response.json()

    print(f"[bold]UV Stars:[/bold] {data['stargazerscount']}")

    Run without manual installation:

    uv run script.py
    

    UV will automatically create a temporary environment with the required dependencies.

    Python Version Management

    UV can manage Python installations without requiring pyenv:

    # List available Python versions
    

    uv python list

    Install a specific Python version

    uv python install 3.12

    Install multiple versions

    uv python install 3.11 3.12 3.13

    Use a specific version for the project

    uv python pin 3.12

    Find the path of an installed Python

    uv python find 3.12

    Setting Python Version per Project

    # Pin Python version for this project
    

    uv python pin 3.11

    .python-version file will be created/updated

    cat .python-version

    Output: 3.11

    Tool Management with uv tool

    UV can install and run Python CLI tools globally:

    # Install a tool globally
    

    uv tool install ruff

    uv tool install black

    uv tool install httpie

    Run a tool without installing (like npx)

    uvx ruff check .

    uvx black --check .

    List installed tools

    uv tool list

    Update a tool

    uv tool upgrade ruff

    Uninstall a tool

    uv tool uninstall ruff

    uvx is a shortcut for uv tool run. It is useful for running tools once without permanently installing them:
    # Run a specific version
    

    uvx ruff@0.3.0 check .

    Run from a different package

    uvx --from httpie http GET https://api.github.com

    Building and Publishing Packages

    Building a Package

    # Build source distribution and wheel
    

    uv build

    Results will be in the dist/ folder

    ls dist/

    mypackage-0.1.0.tar.gz

    mypackage-0.1.0-py3-none-any.whl

    Publishing to PyPI

    # Publish to PyPI
    

    uv publish

    Publish to TestPyPI

    uv publish --index-url https://test.pypi.org/legacy/

    Publish with token

    uv publish --token pypi-xxxxx

    Configuring pyproject.toml for Publishing

    [project]
    

    name = "my-package"

    version = "0.1.0"

    description = "My awesome package"

    readme = "README.md"

    license = { text = "MIT" }

    authors = [

    { name = "Ruby Abdullah", email = "ruby@example.com" },

    ]

    requires-python = ">=3.11"

    dependencies = [

    "requests>=2.28",

    ]

    [build-system]

    requires = ["hatchling"]

    build-backend = "hatchling.build"

    [project.urls]

    Homepage = "https://github.com/user/my-package"

    Migration from pip/Poetry

    Migrating from pip + requirements.txt

    # Create a new UV project
    

    uv init my-project

    cd my-project

    Import from requirements.txt

    uv add $(cat requirements.txt | grep -v '^#' | grep -v '^

    | tr '\n' ' ')

    Or use uv pip for direct compatibility

    uv pip install -r requirements.txt

    Migrating from Poetry

    UV can directly read pyproject.toml from Poetry projects. Migration steps:

  • Remove the poetry.lock file
  • Change the build system in pyproject.toml:
  • # From (Poetry)
    

    [build-system]

    requires = ["poetry-core"]

    build-backend = "poetry.core.masonry.api"

    To (Hatchling, recommended by UV)

    [build-system]

    requires = ["hatchling"]

    build-backend = "hatchling.build"

  • Move dependency groups:
  • # From (Poetry)
    

    [tool.poetry.dependencies]

    python = "^3.11"

    requests = "^2.28"

    [tool.poetry.group.dev.dependencies]

    pytest = "^7.0"

    To (PEP 621 standard)

    [project]

    requires-python = ">=3.11"

    dependencies = [

    "requests>=2.28",

    ]

    [dependency-groups]

    dev = [

    "pytest>=7.0",

    ]

  • Generate a new lockfile:
  • uv lock
    

    uv sync

    Comparison: UV vs pip vs Poetry vs Conda

    | Feature | UV | pip | Poetry | Conda |

    |---------|-----|-----|--------|-------|

    | Install speed | Very fast (Rust) | Slow | Medium | Slow |

    | Lockfile | Yes (uv.lock) | No (needs pip-tools) | Yes (poetry.lock) | Yes (conda-lock) |

    | Built-in virtual env | Yes | No (needs virtualenv) | Yes | Yes |

    | Python version mgmt | Yes | No (needs pyenv) | No | Yes |

    | Dependency resolver | Yes (fast) | Yes (slow) | Yes (medium) | Yes (very slow) |

    | Standards compliance | PEP 621/723 | PEP 621 | Custom format | Custom format |

    | Binary size | Small (~30MB) | Small | Medium | Large (>500MB) |

    | Global tool management | Yes (uv tool) | No (needs pipx) | No | No |

    | Cross-platform | Yes | Yes | Yes | Yes |

    | Non-Python packages | No | No | No | Yes |

    When to Use What?

    Practical Example: Setting Up an ML Project with UV

    Let's build a complete Machine Learning project from scratch using UV.

    Step 1: Initialize the Project

    uv init ml-sentiment-analyzer --python 3.12
    

    cd ml-sentiment-analyzer

    Step 2: Install ML Dependencies

    # Core ML dependencies
    

    uv add numpy pandas scikit-learn

    NLP dependencies

    uv add transformers torch datasets

    API framework

    uv add fastapi uvicorn

    Utilities

    uv add pydantic python-dotenv loguru

    Dev dependencies

    uv add --dev pytest pytest-cov ruff mypy httpx

    Step 3: Project Structure

    ml-sentiment-analyzer/
    

    ├── .python-version

    ├── pyproject.toml

    ├── uv.lock

    ├── README.md

    ├── src/

    │ ├── init.py

    │ ├── model.py

    │ ├── preprocess.py

    │ ├── train.py

    │ └── api.py

    ├── tests/

    │ ├── init.py

    │ ├── testmodel.py

    │ └── testapi.py

    ├── data/

    │ └── .gitkeep

    └── .env

    Create the folder structure:

    mkdir -p src tests data
    

    touch src/init.py tests/init.py data/.gitkeep

    Step 4: Data Preprocessing

    Create src/preprocess.py:

    import re
    

    import pandas as pd

    from loguru import logger

    def cleantext(text: str) -> str:

    """Clean text from noise."""

    text = text.lower()

    text = re.sub(r"http\S+|www\S+|https\S+", "", text)

    text = re.sub(r"[^a-zA-Z\s]", "", text)

    text = re.sub(r"\s+", " ", text).strip()

    return text

    def loadandpreprocess(filepath: str) -> pd.DataFrame:

    """Load and preprocess dataset."""

    logger.info(f"Loading data from {filepath}")

    df = pd.readcsv(filepath)

    df["cleantext"] = df["text"].apply(cleantext)

    df = df.dropna(subset=["cleantext"])

    logger.info(f"Preprocessed {len(df)} samples")

    return df

    Step 5: Model Training

    Create src/model.py:

    import pickle
    

    from pathlib import Path

    from sklearn.featureextraction.text import TfidfVectorizer

    from sklearn.linearmodel import LogisticRegression

    from sklearn.pipeline import Pipeline

    from sklearn.metrics import classificationreport

    from loguru import logger

    class SentimentModel:

    """Sentiment analysis model using TF-IDF + Logistic Regression."""

    def init(self):

    self.pipeline = Pipeline([

    ("tfidf", TfidfVectorizer(maxfeatures=10000, ngramrange=(1, 2))),

    ("classifier", LogisticRegression(maxiter=1000, C=1.0)),

    ])

    def train(self, texts: list[str], labels: list[int]) -> dict:

    """Train the model."""

    logger.info(f"Training model with {len(texts)} samples")

    self.pipeline.fit(texts, labels)

    predictions = self.pipeline.predict(texts)

    report = classificationreport(labels, predictions, outputdict=True)

    logger.info(f"Training accuracy: {report['accuracy']:.4f}")

    return report

    def predict(self, texts: list[str]) -> list[int]:

    """Predict sentiment."""

    return self.pipeline.predict(texts).tolist()

    def predictproba(self, texts: list[str]) -> list[list[float]]:

    """Predict sentiment probabilities."""

    return self.pipeline.predictproba(texts).tolist()

    def save(self, path: str) -> None:

    """Save model to disk."""

    Path(path).parent.mkdir(parents=True, existok=True)

    with open(path, "wb") as f:

    pickle.dump(self.pipeline, f)

    logger.info(f"Model saved to {path}")

    def load(self, path: str) -> None:

    """Load model from disk."""

    with open(path, "rb") as f:

    self.pipeline = pickle.load(f)

    logger.info(f"Model loaded from {path}")

    Step 6: FastAPI Application

    Create src/api.py:

    from fastapi import FastAPI, HTTPException
    

    from pydantic import BaseModel

    from src.model import SentimentModel

    app = FastAPI(title="Sentiment Analyzer API", version="1.0.0")

    model = SentimentModel()

    MODELPATH = "models/sentimentmodel.pkl"

    try:

    model.load(MODELPATH)

    except FileNotFoundError:

    print("Warning: Model not found. Train the model first.")

    class PredictionRequest(BaseModel):

    texts: list[str]

    class PredictionResponse(BaseModel):

    predictions: list[int]

    probabilities: list[list[float]]

    labels: list[str]

    @app.post("/predict", responsemodel=PredictionResponse)

    async def predict(request: PredictionRequest):

    if not request.texts:

    raise HTTPException(statuscode=400, detail="Texts cannot be empty")

    predictions = model.predict(request.texts)

    probabilities = model.predictproba(request.texts)

    labels = ["negative" if p == 0 else "positive" for p in predictions]

    return PredictionResponse(

    predictions=predictions,

    probabilities=probabilities,

    labels=labels,

    )

    @app.get("/health")

    async def health():

    return {"status": "healthy"}

    Step 7: Tests

    Create tests/testmodel.py:

    import pytest
    

    from src.model import SentimentModel

    @pytest.fixture

    def model():

    return SentimentModel()

    @pytest.fixture

    def sampledata():

    texts = [

    "this product is amazing and wonderful",

    "terrible experience very disappointed",

    "love this so much great quality",

    "worst purchase ever do not buy",

    ]

    labels = [1, 0, 1, 0]

    return texts, labels

    def testtrain(model, sampledata):

    texts, labels = sampledata

    report = model.train(texts, labels)

    assert "accuracy" in report

    assert report["accuracy"] > 0

    def testpredict(model, sampledata):

    texts, labels = sampledata

    model.train(texts, labels)

    predictions = model.predict(["this is great"])

    assert len(predictions) == 1

    assert predictions[0] in [0, 1]

    def testpredictproba(model, sampledata):

    texts, labels = sampledata

    model.train(texts, labels)

    proba = model.predictproba(["this is great"])

    assert len(proba) == 1

    assert len(proba[0]) == 2

    assert abs(sum(proba[0]) - 1.0) < 1e-6

    Step 8: Running the Project

    # Run tests
    

    uv run pytest tests/ -v

    Run the API server

    uv run uvicorn src.api:app --reload --host 0.0.0.0 --port 8000

    Run the training script

    uv run python src/train.py

    Step 9: Linting and Formatting Configuration

    Add Ruff configuration to pyproject.toml:

    [tool.ruff]
    

    target-version = "py312"

    line-length = 88

    [tool.ruff.lint]

    select = ["E", "F", "I", "N", "UP", "B"]

    [tool.pytest.inioptions]

    testpaths = ["tests"]

    Run linting:

    uv run ruff check src/ tests/
    

    uv run ruff format src/ tests/

    Step 10: Dockerfile for Production

    FROM python:3.12-slim
    
    

    COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv

    WORKDIR /app

    COPY pyproject.toml uv.lock ./

    RUN uv sync --no-dev --frozen

    COPY src/ src/

    COPY models/ models/

    CMD ["uv", "run", "uvicorn", "src.api:app", "--host", "0.0.0.0", "--port", "8000"]

    Tips and Best Practices

  • Always commit uv.lock: The lockfile ensures reproducible builds across all environments
  • Use uv run: Avoid manually activating venv, use uv run to execute commands
  • Separate dev dependencies: Use --dev for tools only needed during development
  • Use uvx for one-off tools: No need to globally install rarely-used tools
  • Pin Python version: Use uv python pin to ensure consistent Python versions
  • Cache in CI/CD: Cache the ~/.cache/uv folder in CI/CD to speed up builds
  • Use constraint files: For large projects, use constraint files to control dependency versions
  • CI/CD Configuration (GitHub Actions)

    name: CI
    

    on: [push, pullrequest]

    jobs:

    test:

    runs-on: ubuntu-latest

    steps:

    • uses: actions/checkout@v4
    • uses: astral-sh/setup-uv@v4
    with:

    version: "latest"

    • run: uv sync --dev
    • run: uv run pytest
    • run: uv run ruff check .

    Conclusion

    UV is a revolution in Python tooling. With speeds 10-100x faster than pip, all-in-one capabilities replacing pip, virtualenv, pyenv, and poetry, plus support for modern Python standards (PEP 621, PEP 723), UV is the ideal choice for new Python projects.

    UV's standout features include fast and reliable dependency management, automatic lockfiles for reproducible builds, integrated Python version management, and the ability to run scripts with inline dependencies. For ML projects, UV provides a much smoother development experience compared to traditional tools.

    Start using UV in your new projects, and consider gradually migrating existing projects. With a rapidly growing community and support from the Astral team, UV is the future of package management in Python.

    Related Articles

    Flower (flwr): A Complete Guide to Federated Learning in Python

    Tutorial Lengkap Flower (flwr): Framework Federated Learning dengan Python Federated learning adalah paradigma machine l...

    Complete Aisuite Tutorial: Unified Multi-LLM Interface by Andrew Ng

    Tutorial Lengkap Aisuite: Unified Multi-LLM Interface dari Andrew Ng Apa itu Aisuite? Aisuite adalah library Python open...

    Complete Neo4j Tutorial: Graph Database for Knowledge Graphs and AI

    Tutorial Lengkap Neo4j: Graph Database untuk Knowledge Graphs dan AI Graph database telah menjadi komponen penting dalam...

    CatBoost Tutorial: Gradient Boosting for Tabular Data with Automatic Categorical Feature Handling

    Tutorial CatBoost: Gradient Boosting untuk Data Tabular dengan Penanganan Fitur Kategorikal Otomatis CatBoost (Categoric...