The Complete Guide to Python uv

    A comprehensive, practical guide to mastering Python’s fastest package manager

    Learning Paths

    Choose your journey based on your experience level:

    πŸš€ Quick Start (15 minutes)

    Sections: 2, 3, 5.1

    πŸ“š Complete Beginner (2-3 hours)

    Sections: 1-8 + Hands-on Labs

    πŸ”§ Migration Path (30 minutes)

    Sections: 14, 13, 16

    🎯 Advanced User (1 hour)

    Sections: 10-12, 15, 17

    Table of Contents

    Part I: Fundamentals

    1. Introduction
    2. What is uv?
    3. Installation & Setup
    4. Core Concepts
    5. Your First Project

    Part II: Essential Skills

    1. Package Management
    2. Virtual Environments
    3. Python Version Management
    4. Project Configuration

    Part III: Advanced Usage

    1. Workspaces & Monorepos
    2. Tool Management
    3. Custom Scripts & Automation
    4. CI/CD Integration

    Part IV: Production & Optimization

    1. Migration Strategies
    2. Best Practices
    3. Performance Optimization
    4. Troubleshooting Guide

    Part V: Reference

    1. Quick Reference
    2. Expert Tips & Tricks
    3. Hands-on Labs
    4. Resources & Community

    1. Introduction

    Welcome to the comprehensive guide to uv, the revolutionary Python package and project manager that’s transforming how we work with Python environments. This guide will take you from zero to expert with practical examples, real-world scenarios, and hands-on exercises.

    πŸ“‹ Prerequisites

    Minimum Requirements:

    • Basic command line familiarity
    • Python 3.8+ installed
    • Text editor or IDE

    Recommended Knowledge:

    • Python development experience
    • Understanding of pip and virtual environments
    • Basic Git knowledge

    🎯 Learning Objectives

    By completing this guide, you will:

    βœ… Understand uv’s architecture and benefits
    βœ… Install and configure uv for your development environment
    βœ… Manage packages and dependencies efficiently
    βœ… Create and maintain virtual environments
    βœ… Handle multiple Python versions seamlessly
    βœ… Optimize your development workflow
    βœ… Migrate existing projects to uv
    βœ… Troubleshoot common issues confidently

    πŸ‘₯ Target Audience

    mindmap
      root((uv Users))
        Beginners
          New to Python
          Coming from other languages
          Students and learners
        Intermediate
          Python developers
          Data scientists
          Web developers
        Advanced
          DevOps engineers
          Package maintainers
          Team leads
        Organizations
          Development teams
          Enterprise environments
          Open source projects

    ⏱️ Time Investment

    Learning PathTime RequiredSections
    Quick Start15-30 minutesEssential commands and basic usage
    Foundation2-3 hoursComplete understanding of core features
    Professional4-6 hoursAdvanced features and best practices
    Expert8+ hoursAll sections + hands-on labs

    πŸš€ What Makes This Guide Different

    1. Practical Focus: Real examples from actual projects
    2. Progressive Learning: Builds from simple to complex concepts
    3. Visual Learning: Extensive use of diagrams and flowcharts
    4. Hands-on Labs: Practice exercises with solutions
    5. Performance Focus: Optimization tips throughout
    6. Migration Support: Complete transition guides from other tools

    πŸ“ˆ uv Adoption Journey

    journey
        title Your uv Learning Journey
        section Discovery
          Read about uv: 3: You
          Compare with pip: 4: You
          See speed demos: 5: You
        section First Steps
          Install uv: 4: You
          Create first project: 5: You
          Install packages: 5: You
        section Proficiency
          Manage environments: 5: You
          Handle Python versions: 4: You
          Configure projects: 5: You
        section Mastery
          Optimize workflows: 5: You
          Lead team adoption: 5: You, Team
          Contribute back: 5: You, Community

    2. What is uv?

    uv is a lightning-fast Python package installer and resolver written in Rust by the Astral team. Think of it as pip’s supersonic successor that doesn’t just install packagesβ€”it revolutionizes your entire Python development workflow.

    πŸ” The Big Picture

    graph TB
        subgraph "Traditional Python Ecosystem"
            A[pip] --> A1[Package Installation]
            B[venv] --> B1[Virtual Environments]
            C[pip-tools] --> C1[Dependency Resolution]
            D[pyenv] --> D1[Python Version Management]
            E[setuptools] --> E1[Project Building]
        end
    
        subgraph "uv Unified Ecosystem"
            F[uv] --> F1[Lightning-Fast Installation]
            F --> F2[Smart Environment Management]
            F --> F3[Advanced Dependency Resolution]
            F --> F4[Seamless Python Management]
            F --> F5[Modern Project Building]
        end
    
        style F fill:#1e88e5,color:#fff
        style F1 fill:#43a047,color:#fff
        style F2 fill:#43a047,color:#fff
        style F3 fill:#43a047,color:#fff
        style F4 fill:#43a047,color:#fff
        style F5 fill:#43a047,color:#fff

    ⚑ Performance Revolution

    uv isn’t just fasterβ€”it’s 10-100x faster than traditional tools. Here’s why:

    Traditional Approachuv ApproachResult
    Python-based toolsRust-native implementationMassive speed boost
    Sequential operationsParallel processingConcurrent execution
    Network round-tripsIntelligent cachingReduced latency
    Full dependency treesIncremental resolutionFaster updates

    πŸ—οΈ Architecture Comparison

    architecture-beta
        group traditional(logos:python)[Traditional Tools]
    
        service pip(logos:python)[pip] in traditional
        service venv(logos:python)[venv] in traditional
        service piptools(logos:python)[pip-tools] in traditional
    
        group modern(logos:rust)[uv (Rust-powered)]
    
        service resolver(logos:gear)[Fast Resolver] in modern
        service installer(logos:download)[Parallel Installer] in modern
        service manager(logos:cog)[Environment Manager] in modern
    
        pip:R --> L:resolver
        venv:R --> L:manager
        piptools:R --> L:resolver

    πŸš€ Key Capabilities

    1. Drop-in Compatibility

    # Replace pip commands directly
    pip install requests    β†’    uv add requests
    pip install -r req.txt  β†’    uv add -r req.txt
    pip freeze             β†’    uv pip freeze
    Bash

    2. Unified Workflow

    flowchart LR
        A[Project Init] --> B[Add Dependencies]
        B --> C[Create Environment]
        C --> D[Install Packages]
        D --> E[Run Application]
    
        A1[uv init] --> B1[uv add]
        B1 --> C1[uv venv]
        C1 --> D1[uv sync]
        D1 --> E1[uv run]
    
        style A1 fill:#1e88e5,color:#fff
        style B1 fill:#1e88e5,color:#fff
        style C1 fill:#1e88e5,color:#fff
        style D1 fill:#1e88e5,color:#fff
        style E1 fill:#1e88e5,color:#fff

    3. Smart Dependency Resolution

    graph TD
        A[Package Request] --> B{Check Compatibility}
        B -->|Compatible| C[Select Best Version]
        B -->|Conflict| D[Advanced Resolution]
    
        D --> E[Backtrack Algorithm]
        E --> F[Find Compatible Set]
        F --> G[Generate Lock File]
    
        C --> H[Install Package]
        G --> H
    
        style A fill:#fff3e0
        style C fill:#e8f5e8
        style G fill:#e3f2fd
        style H fill:#c8e6c9

    πŸ“Š Real-World Impact

    Case Study: A typical Django project with 50 dependencies

    • pip: 45 seconds installation
    • poetry: 30 seconds installation
    • uv: 3 seconds installation

    Speed Comparison Chart

    xychart-beta
        title "Installation Time Comparison (50 packages)"
        x-axis [pip, poetry, conda, uv]
        y-axis "Time (seconds)" 0 --> 50
        bar [45, 30, 25, 3]

    🎯 Why Choose uv?

    FeatureTraditional Toolsuv
    SpeedSlowπŸš€ 10-100x faster
    MemoryHigh usage🧠 Efficient
    CommandsMultiple tools🎯 Unified interface
    ResolutionBasicπŸ”¬ Advanced algorithms
    CachingLimitedπŸ“¦ Intelligent
    Python VersionsExternal tools🐍 Built-in management
    Lock FilesBasicπŸ”’ Comprehensive

    🌟 The uv Philosophy

    mindmap
      root((uv Philosophy))
        Speed
          Rust Performance
          Parallel Execution
          Smart Caching
        Simplicity
          Single Tool
          Intuitive Commands
          Minimal Configuration
        Reliability
          Deterministic Builds
          Advanced Resolution
          Comprehensive Testing
        Compatibility
          Drop-in Replacement
          Standard Formats
          Ecosystem Integration

    uv vs pip

    • βœ… 10-100x faster installation
    • βœ… Better dependency resolution
    • βœ… Built-in virtual environment support
    • βœ… Modern project management

    uv vs Poetry

    • βœ… Significantly faster
    • βœ… Simpler configuration
    • βœ… Better performance
    • βš–οΈ Similar dependency management features

    uv vs Conda

    • βœ… Pure Python focus
    • βœ… Faster resolution
    • βœ… Smaller footprint
    • ❌ No system-level packages

    πŸŽ‰ Success Stories

    “We migrated our entire CI/CD pipeline to uv and reduced build times from 10 minutes to 2 minutes.”
    β€” Senior DevOps Engineer, Tech Startup

    “uv transformed our development workflow. Dependencies that took minutes now install in seconds.”
    β€” Data Science Team Lead, Fortune 500


    3. Installation & Setup

    Getting uv up and running is straightforward, but choosing the right installation method for your use case is important. This section covers all installation methods with platform-specific guidance.

    πŸ” Pre-Installation Checklist

    Before installing uv, ensure you have:

    • βœ… Python 3.8+ (check with python --version)
    • βœ… Internet connection for downloading packages
    • βœ… Command line access (Terminal, PowerShell, Command Prompt)
    • βœ… Admin rights (for system-wide installation)

    πŸš€ Installation Methods

    Choose the method that best fits your needs:

    flowchart TD
        A[Choose Installation Method] --> B{Your Situation}
    
        B -->|New to Python| C[Method 1: pip install]
        B -->|System Admin| D[Method 2: pipx install]
        B -->|Quick Setup| E[Method 3: Installer Script]
        B -->|Package Manager User| F[Method 4: brew/scoop]
        B -->|Advanced User| G[Method 5: From Source]
    
        C --> H[Simple & Fast]
        D --> I[Isolated & Clean]
        E --> J[One Command Setup]
        F --> K[Integrated Management]
        G --> L[Latest Features]
    
        style C fill:#4caf50,color:#fff
        style D fill:#2196f3,color:#fff
        style E fill:#ff9800,color:#fff
        style F fill:#9c27b0,color:#fff
        style G fill:#f44336,color:#fff

    Best for: Quick start, existing Python environments

    # Install uv globally
    pip install uv
    
    # Or install for current user only
    pip install --user uv
    Bash

    Verification:

    uv --version
    # Expected output: uv 0.4.0 (or latest version)
    Bash

    Best for: Clean installation, avoiding conflicts

    # Install pipx first (if not already installed)
    pip install pipx
    
    # Install uv with pipx
    pipx install uv
    
    # Ensure pipx bin directory is in PATH
    pipx ensurepath
    Bash

    Benefits:

    • βœ… Isolated from system Python
    • βœ… Automatic PATH management
    • βœ… Easy upgrades with pipx upgrade uv

    Best for: Automated setups, fresh systems

    macOS/Linux:

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

    Windows (PowerShell):

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

    What the script does:

    1. Downloads the latest uv binary
    2. Installs to ~/.local/bin (Unix) or %USERPROFILE%\.local\bin (Windows)
    3. Updates your shell configuration
    4. Verifies the installation

    Method 4: Package Managers

    macOS (Homebrew):

    # Install Homebrew (if needed)
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    
    # Install uv
    brew install uv
    Bash

    Windows (Scoop):

    # Install Scoop (if needed)
    Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
    irm get.scoop.sh | iex
    
    # Install uv
    scoop install uv
    Bash

    Linux (Various):

    # Arch Linux
    pacman -S uv
    
    # Fedora
    dnf install uv
    
    # Ubuntu/Debian (via snap)
    snap install uv
    Bash

    Method 5: From Source (Advanced)

    Best for: Latest features, contributing to development

    # Prerequisites: Rust toolchain
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    
    # Clone and build
    git clone https://github.com/astral-sh/uv.git
    cd uv
    cargo build --release
    
    # Install
    cargo install --path .
    Bash

    πŸ”§ Post-Installation Setup

    1. Verify Installation

    # Check version
    uv --version
    
    # Check help
    uv --help
    
    # Test basic functionality
    uv pip list
    Bash

    2. Configure Shell Integration (Optional)

    For enhanced experience, add to your shell config:

    Bash (~/.bashrc):

    # uv completions
    eval "$(uv generate-shell-completion bash)"
    
    # uv aliases (optional)
    alias pip="uv pip"
    alias python="uv run python"
    Bash

    Zsh (~/.zshrc):

    # uv completions
    eval "$(uv generate-shell-completion zsh)"
    
    # uv aliases (optional)
    alias pip="uv pip"
    alias python="uv run python"
    Bash

    PowerShell (Profile):

    # Add to your PowerShell profile
    Invoke-Expression (uv generate-shell-completion powershell)
    Bash

    3. Set Up Configuration (Optional)

    Create ~/.config/uv/uv.toml (Unix) or %APPDATA%\uv\uv.toml (Windows):

    [tool.uv]
    # Default Python version
    python = "3.11"
    
    # Cache directory
    cache-dir = "~/.cache/uv"
    
    # Default index URL
    index-url = "https://pypi.org/simple"
    
    # Concurrent downloads
    concurrent-downloads = 10
    
    # Timeout settings
    timeout = 30
    Bash

    πŸ” Installation Verification

    Run this comprehensive verification script:

    # Create a test directory
    mkdir uv-test && cd uv-test
    
    # Initialize a project
    uv init test-project
    cd test-project
    
    # Add a package
    uv add requests
    
    # Run a simple test
    uv run python -c "import requests; print('βœ… uv is working correctly!')"
    
    # Clean up
    cd ../..
    rm -rf uv-test
    Bash

    Expected output:

    βœ… uv is working correctly!
    Bash

    πŸ› οΈ Troubleshooting Installation

    Common Issues and Solutions

    flowchart TD
        A[Installation Issue] --> B{Error Type}
    
        B -->|Permission Denied| C[Use --user flag]
        B -->|Command Not Found| D[Check PATH]
        B -->|Network Error| E[Check Internet/Proxy]
        B -->|Version Conflict| F[Use pipx or venv]
    
        C --> G[pip install --user uv]
        D --> H[Add ~/.local/bin to PATH]
        E --> I[Configure proxy settings]
        F --> J[pipx install uv]
    
        style A fill:#ffeb3b
        style G fill:#4caf50,color:#fff
        style H fill:#4caf50,color:#fff
        style I fill:#4caf50,color:#fff
        style J fill:#4caf50,color:#fff

    Issue 1: Permission Denied

    Problem: pip install uv fails with permission errors

    Solutions:

    # Option 1: User installation
    pip install --user uv
    
    # Option 2: Use pipx
    pipx install uv
    
    # Option 3: Virtual environment
    python -m venv uv-env
    source uv-env/bin/activate  # Unix
    # or: uv-env\Scripts\activate  # Windows
    pip install uv
    Bash

    Issue 2: Command Not Found

    Problem: uv command not recognized after installation

    Solutions:

    # Check if uv is in PATH
    which uv  # Unix
    where uv  # Windows
    
    # Add to PATH if needed (Unix)
    echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
    source ~/.bashrc
    
    # Add to PATH (Windows - PowerShell)
    $env:PATH += ";$env:USERPROFILE\.local\bin"
    Bash

    Issue 3: Network/Proxy Issues

    Problem: Cannot download uv or packages

    Solutions:

    # Set proxy for pip
    pip install --proxy http://user:pass@proxy.server:port uv
    
    # Set proxy environment variables
    export HTTP_PROXY=http://proxy.server:port
    export HTTPS_PROXY=http://proxy.server:port
    
    # Use different index
    pip install -i https://pypi.org/simple/ uv
    Bash

    Issue 4: Python Version Conflicts

    Problem: uv requires Python 3.8+ but system has older version

    Solutions:

    # Install newer Python version
    # macOS
    brew install python@3.11
    
    # Windows
    # Download from python.org
    
    # Linux
    sudo apt-get install python3.11
    
    # Use specific Python version
    python3.11 -m pip install uv
    Bash

    🎯 Installation Best Practices

    1. Use pipx for system-wide installation
    2. Use pip for project-specific installation
    3. Use package managers for system integration
    4. Keep uv updated regularly
    5. Verify installation after setup

    πŸ“Š Installation Method Comparison

    MethodSpeedIsolationUpdatesBest For
    pipFastPoorManualQuick start
    pipxFastExcellentEasyProduction
    ScriptMediumGoodManualCI/CD
    Package ManagerMediumGoodAutomaticSystem integration
    From SourceSlowPoorManualDevelopment

    ⬆️ Upgrading uv

    Keep uv updated for the latest features and performance improvements:

    # pipx
    pipx upgrade uv
    
    # pip
    pip install --upgrade uv
    
    # Homebrew
    brew upgrade uv
    
    # Check latest version
    uv --version
    Bash

    4. Core Concepts

    Understanding uv’s fundamental concepts is crucial for leveraging its full potential. This section breaks down the key components and how they work together to create a seamless Python development experience.

    πŸ—οΈ uv’s Architecture

    graph TB
        subgraph "uv Core System"
            A[uv CLI] --> B[Package Resolver]
            A --> C[Environment Manager]
            A --> D[Python Manager]
            A --> E[Project Manager]
    
            B --> F[Dependency Graph]
            B --> G[Version Selection]
            B --> H[Conflict Resolution]
    
            C --> I[Virtual Environments]
            C --> J[Tool Environments]
    
            D --> K[Python Discovery]
            D --> L[Version Installation]
    
            E --> M[Project Configuration]
            E --> N[Lock Files]
            E --> O[Build System]
        end
    
        subgraph "External Systems"
            P[PyPI Registry]
            Q[File System]
            R[Cache Storage]
        end
    
        B <--> P
        C <--> Q
        A <--> R
    
        style A fill:#1e88e5,color:#fff
        style B fill:#43a047,color:#fff
        style C fill:#ff9800,color:#fff
        style D fill:#9c27b0,color:#fff
        style E fill:#f44336,color:#fff

    πŸ”‘ Fundamental Concepts

    1. Projects vs Packages

    graph LR
        A[Python Code] --> B{Type}
        B -->|Application| C[Project]
        B -->|Library| D[Package]
    
        C --> E[pyproject.toml]
        C --> F[uv.lock]
        C --> G[Virtual Environment]
    
        D --> H[setup.py/pyproject.toml]
        D --> I[Published to PyPI]
        D --> J[Consumed by Projects]
    
        style C fill:#e3f2fd
        style D fill:#f3e5f5

    Projects are applications you’re developing:

    • Web applications
    • Data analysis scripts
    • CLI tools

    Packages are reusable libraries:

    • requests, numpy, django
    • Your internal company libraries
    • Open source contributions

    2. Dependency Resolution

    uv uses advanced algorithms to solve the complex puzzle of package dependencies:

    flowchart TD
        A[Your Requirements] --> B[Fetch Package Metadata]
        B --> C[Build Dependency Tree]
        C --> D{Conflicts Found?}
    
        D -->|No| E[Select Versions]
        D -->|Yes| F[Backtrack Algorithm]
    
        F --> G[Try Alternative Versions]
        G --> H{Solution Found?}
        H -->|Yes| E
        H -->|No| I[Report Conflict]
    
        E --> J[Generate Lock File]
        J --> K[Install Packages]
    
        style A fill:#fff3e0
        style E fill:#e8f5e8
        style F fill:#ffebee
        style I fill:#ffcdd2
        style K fill:#c8e6c9

    Key Features:

    • Parallel Resolution: Multiple dependency branches resolved simultaneously
    • Conflict Detection: Early identification of incompatible requirements
    • Version Optimization: Selects the best compatible versions
    • Backtracking: Intelligent retry when conflicts are found

    3. Virtual Environments

    Virtual environments provide isolated spaces for your project dependencies:

    architecture-beta
        group system(logos:python)[System Python]
    
        service interpreter(logos:python)[Python 3.11] in system
        service stdlib(logos:book)[Standard Library] in system
        service globals(logos:globe)[Global Packages] in system
    
        group project1(logos:folder)[Project A]
        service venv1(logos:box)[Virtual Env] in project1
        service deps1(logos:package)[Dependencies] in project1
    
        group project2(logos:folder)[Project B]
        service venv2(logos:box)[Virtual Env] in project2
        service deps2(logos:package)[Dependencies] in project2
    
        interpreter:L --> R:venv1
        interpreter:L --> R:venv2
        stdlib:L --> R:venv1
        stdlib:L --> R:venv2

    Benefits:

    • βœ… Isolation: Projects don’t interfere with each other
    • βœ… Reproducibility: Consistent environments across machines
    • βœ… Cleanliness: Easy to reset or remove environments
    • βœ… Version Control: Different Python versions per project

    4. Lock Files (uv.lock)

    Lock files ensure reproducible builds by pinning exact versions:

    graph TD
        A[pyproject.toml] --> B[Abstract Dependencies]
        B --> C[uv resolve]
        C --> D[uv.lock]
        D --> E[Concrete Dependencies]
    
        B --> F["requests>=2.28.0"]
        E --> G["requests==2.31.0</br>certifi==2023.7.22</br>charset-normalizer==3.2.0</br>idna==3.4urllib3==2.0.4"]
    
        style A fill:#fff3e0
        style D fill:#e3f2fd
        style F fill:#ffebee
        style G fill:#e8f5e8

    Lock File Contents:

    • Exact versions of all dependencies
    • Checksums for security verification
    • Source information (PyPI, Git, local)
    • Platform-specific variations

    5. Workspaces

    For multi-package projects, workspaces provide unified management:

    graph TD
        A[Workspace Root] --> B[shared-utils/]
        A --> C[web-app/]
        A --> D[api-service/]
        A --> E[cli-tool/]
    
        B --> F[pyproject.toml]
        C --> G[pyproject.toml]
        D --> H[pyproject.toml]
        E --> I[pyproject.toml]
    
        A --> J[workspace uv.lock]
    
        C --> K["depends on shared-utils"]
        D --> L["depends on shared-utils"]
    
        style A fill:#1e88e5,color:#fff
        style J fill:#ff9800,color:#fff

    🎯 Core Commands Overview

    uv’s commands are organized into logical groups:

    mindmap
      root((uv Commands))
        Project Management
          init
          add
          remove
          sync
          lock
          build
          publish
        Environment
          venv
          activate
        Python Management
          python list
          python install
          python find
          python pin
        Tool Management
          tool install
          tool run
          tool list
          tool uninstall
        Package Operations
          pip install
          pip list
          pip show
          pip freeze

    πŸ”„ uv Workflow Patterns

    Pattern 1: New Project Workflow

    sequenceDiagram
        participant Dev as Developer
        participant uv as uv CLI
        participant FS as File System
        participant PyPI as Package Registry
    
        Dev->>uv: uv init my-project
        uv->>FS: Create project structure
        uv->>Dev: Project created
    
        Dev->>uv: uv add requests
        uv->>PyPI: Resolve dependencies
        uv->>FS: Update pyproject.toml & uv.lock
        uv->>Dev: Package added
    
        Dev->>uv: uv run python main.py
        uv->>FS: Ensure environment exists
        uv->>Dev: Execute in project environment

    Pattern 2: Existing Project Workflow

    sequenceDiagram
        participant Dev as Developer
        participant uv as uv CLI
        participant Git as Git Repository
        participant FS as File System
    
        Dev->>Git: git clone project
        Git->>FS: Download project files
    
        Dev->>uv: uv sync
        uv->>FS: Read uv.lock
        uv->>FS: Create virtual environment
        uv->>FS: Install exact dependencies
        uv->>Dev: Environment ready
    
        Dev->>uv: uv run pytest
        uv->>Dev: Execute tests

    πŸ“Š uv vs Traditional Tools: Concept Mapping

    Traditionaluv CommandPurpose
    pip install packageuv add packageAdd dependency
    pip install -r requirements.txtuv add -r requirements.txtInstall from file
    python -m venv .venvuv venvCreate environment
    source .venv/bin/activateuv runUse environment
    pip freeze > requirements.txtuv lockLock dependencies
    pip install -e .uv sync --devInstall project

    🧠 Mental Model: The uv Ecosystem

    Think of uv as a unified control center for Python development:

    graph TB
        subgraph "Your Development Environment"
            A[uv] --> B[Project Configuration]
            A --> C[Dependency Management]
            A --> D[Environment Isolation]
            A --> E[Python Version Control]
    
            B --> F[pyproject.toml]
            C --> G[uv.lock]
            D --> H[.venv/]
            E --> I[.python-version]
        end
    
        subgraph "External Resources"
            J[PyPI Packages]
            K[Git Repositories]
            L[Local File System]
            M[Python Distributions]
        end
    
        C <--> J
        C <--> K
        C <--> L
        E <--> M
    
        style A fill:#1e88e5,color:#fff
        style F fill:#4caf50,color:#fff
        style G fill:#ff9800,color:#fff
        style H fill:#9c27b0,color:#fff
        style I fill:#f44336,color:#fff

    πŸŽ“ Key Principles to Remember

    1. Declarative Configuration: Specify what you want, not how to get it
    2. Reproducible Builds: Lock files ensure consistent environments
    3. Isolation by Default: Every project gets its own environment
    4. Performance First: All operations optimized for speed
    5. Standards Compliant: Uses Python packaging standards

    πŸ’‘ Pro Tips for Understanding uv

    1. Think in Projects: uv organizes around projects, not global environments
    2. Trust the Lock File: It’s your source of truth for exact dependencies
    3. Use uv run: Let uv manage the environment automatically
    4. Read the Output: uv provides helpful information about what it’s doing
    5. Start Simple: Begin with basic commands and gradually explore advanced features

    5. Your First Project

    Your First uv Project

    Let’s create your first project using uv:

    Step 1: Initialize a new project

    uv init my-first-project
    cd my-first-project
    Bash

    This creates:

    my-first-project/
    β”œβ”€β”€ pyproject.toml
    β”œβ”€β”€ README.md
    β”œβ”€β”€ src/
    β”‚   └── my_first_project/
    β”‚       └── __init__.py
    └── .python-version
    Bash

    Step 2: Understanding the project structure

    graph TD
        A[my-first-project/] --> B[pyproject.toml]
        A --> C[README.md]
        A --> D[src/]
        A --> E[.python-version]
    
        D --> F[my_first_project/]
        F --> G[__init__.py]
    
        B --> H[Project Configuration]
        C --> I[Documentation]
        E --> J[Python Version Pin]
        G --> K[Package Code]
    
        style A fill:#e3f2fd
        style B fill:#fff3e0
        style D fill:#f3e5f5

    Step 3: Add your first dependency

    uv add requests
    Bash

    This will:

    1. Add requests to pyproject.toml
    2. Create/update uv.lock
    3. Install the package

    Step 4: Create a simple script

    Create src/my_first_project/main.py:

    import requests
    
    def get_python_version():
        """Fetch Python version from httpbin."""
        response = requests.get('https://httpbin.org/json')
        return response.json()
    
    if __name__ == "__main__":
        data = get_python_version()
        print(f"Response: {data}")
    Python

    Step 5: Run your script

    uv run python src/my_first_project/main.py
    Bash

    Understanding the Workflow

    sequenceDiagram
        participant Dev as Developer
        participant uv as uv CLI
        participant PyPI as PyPI Registry
        participant Env as Virtual Environment
    
        Dev->>uv: uv init project
        uv->>Dev: Creates project structure
    
        Dev->>uv: uv add requests
        uv->>PyPI: Resolve dependencies
        PyPI->>uv: Return package info
        uv->>Env: Install packages
        uv->>Dev: Update pyproject.toml & uv.lock
    
        Dev->>uv: uv run script.py
        uv->>Env: Execute in virtual environment
        Env->>Dev: Return output

    6. Package Management

    Installing Packages

    Basic Installation

    # Install a single package
    uv add numpy
    
    # Install multiple packages
    uv add pandas matplotlib seaborn
    
    # Install with version constraints
    uv add "django>=4.0,<5.0"
    
    # Install from specific index
    uv add --index-url https://pypi.org/simple/ requests
    Bash

    Development Dependencies

    # Add development dependencies
    uv add --dev pytest black flake8
    
    # Add optional dependencies
    uv add --optional docs sphinx
    
    # Add with extras
    uv add "fastapi[all]"
    Bash

    Package Installation Flow

    flowchart TD
        A[uv add package] --> B{Check Cache}
        B -->|Hit| C[Use Cached Version]
        B -->|Miss| D[Download from PyPI]
    
        C --> E[Resolve Dependencies]
        D --> E
    
        E --> F{Conflicts?}
        F -->|Yes| G[Advanced Resolution]
        F -->|No| H[Install Package]
    
        G --> I{Resolvable?}
        I -->|Yes| H
        I -->|No| J[Error Report]
    
        H --> K[Update pyproject.toml]
        K --> L[Update uv.lock]
        L --> M[Installation Complete]
    
        style M fill:#c8e6c9
        style J fill:#ffcdd2

    Removing Packages

    # Remove a package
    uv remove numpy
    
    # Remove multiple packages
    uv remove pandas matplotlib
    
    # Remove development dependencies
    uv remove --dev pytest
    Bash

    Listing Packages

    # List installed packages
    uv pip list
    
    # Show package information
    uv pip show requests
    
    # List outdated packages
    uv pip list --outdated
    Bash

    Package Constraints and Resolution

    Understanding Version Constraints

    graph LR
        A[Version Constraints] --> B[">= 1.0"]
        A --> C["~= 1.4"]
        A --> D["== 1.2.3"]
        A --> E[">= 1.0, < 2.0"]
    
        B --> F[Minimum Version]
        C --> G[Compatible Release]
        D --> H[Exact Version]
        E --> I[Version Range]
    
        style A fill:#1976d2,color:#fff

    Dependency Resolution Process

    graph TB
        A[Start Resolution] --> B[Parse Requirements]
        B --> C[Fetch Package Metadata]
        C --> D[Build Dependency Graph]
        D --> E{Conflicts Detected?}
    
        E -->|Yes| F[Backtrack & Retry]
        E -->|No| G[Select Versions]
    
        F --> H{Max Attempts?}
        H -->|No| C
        H -->|Yes| I[Resolution Failed]
    
        G --> J[Generate Lock File]
        J --> K[Install Packages]
    
        style K fill:#c8e6c9
        style I fill:#ffcdd2

    7. Virtual Environments

    Creating Virtual Environments

    Basic Environment Creation

    # Create a new virtual environment
    uv venv
    
    # Create with specific Python version
    uv venv --python 3.11
    
    # Create with custom name
    uv venv my-env
    
    # Create in specific directory
    uv venv /path/to/my-env
    Bash

    Environment Management Workflow

    flowchart TD
        A[uv venv] --> B{Python Version Specified?}
        B -->|No| C[Use Default Python]
        B -->|Yes| D[Find Specified Version]
    
        C --> E[Create Environment]
        D --> F{Version Available?}
        F -->|Yes| E
        F -->|No| G[Download/Install Python]
        G --> E
    
        E --> H[Install Base Packages]
        H --> I[Environment Ready]
    
        style I fill:#c8e6c9

    Activating Environments

    Manual Activation

    Windows:

    .venv\Scripts\activate
    Bash

    macOS/Linux:

    source .venv/bin/activate
    Bash
    # Run command in virtual environment
    uv run python script.py
    
    # Run with specific environment
    uv run --env my-env python script.py
    
    # Install and run tool
    uv tool run black script.py
    Bash

    Environment Information

    # Show current environment info
    uv venv --show-path
    
    # List all environments
    uv venv --list
    
    # Remove environment
    uv venv --remove my-env
    Bash

    Advanced Environment Features

    Environment Inheritance

    graph TD
        A[System Python] --> B[Base Virtual Environment]
        B --> C[Project Environment]
        C --> D[Development Environment]
    
        A --> E[Global Packages]
        B --> F[Base Dependencies]
        C --> G[Project Dependencies]
        D --> H[Dev Dependencies]
    
        style A fill:#ffeb3b
        style B fill:#ff9800
        style C fill:#2196f3
        style D fill:#4caf50

    Environment Synchronization

    # Sync environment with lock file
    uv sync
    
    # Sync only production dependencies
    uv sync --no-dev
    
    # Sync specific groups
    uv sync --group test
    
    # Force sync (reinstall all)
    uv sync --force
    Bash

    8. Python Version Management

    Managing Python Versions

    Listing Available Python Versions

    # List all available Python versions
    uv python list
    
    # List installed Python versions
    uv python list --installed
    
    # Find specific Python version
    uv python find 3.11
    Bash

    Installing Python Versions

    # Install latest Python 3.11
    uv python install 3.11
    
    # Install specific version
    uv python install 3.11.5
    
    # Install multiple versions
    uv python install 3.10 3.11 3.12
    Bash

    Python Version Resolution

    flowchart TD
        A[Python Version Request] --> B{Exact Version?}
        B -->|Yes| C[Check if Installed]
        B -->|No| D[Find Best Match]
    
        C -->|Found| E[Use Installed]
        C -->|Not Found| F[Download & Install]
    
        D --> G{Multiple Matches?}
        G -->|Yes| H[Use Latest]
        G -->|No| I[Use Single Match]
    
        E --> J[Set as Active]
        F --> J
        H --> J
        I --> J
    
        style J fill:#c8e6c9

    Project-Specific Python Versions

    Using .python-version

    Create a .python-version file:

    3.11.5
    Bash

    uv will automatically use this version for the project.

    Setting Python Version for Project

    # Set Python version for current project
    uv python pin 3.11
    
    # Set specific patch version
    uv python pin 3.11.5
    
    # Use system Python
    uv python pin system
    Bash

    Python Version Hierarchy

    graph TD
        A["Python Version Selection"] --> B[1\. Explicit --python flag]
        B --> C["2\. .python-version file"]
        C --> D["3\. pyproject.toml requires-python"]
        D --> E["4\. Environment variable PYTHON"]
        E --> F["5\. System PATH"]
    
        style A fill:#1976d2,color:#fff
        style B fill:#f44336,color:#fff
        style C fill:#ff9800,color:#fff
        style D fill:#2196f3,color:#fff
        style E fill:#4caf50,color:#fff
        style F fill:#9c27b0,color:#fff

    9. Project Structure and Configuration

    Understanding pyproject.toml

    The pyproject.toml file is the heart of your uv project:

    [project]
    name = "my-awesome-project"
    version = "0.1.0"
    description = "A sample project using uv"
    authors = [
        {name = "Your Name", email = "your.email@example.com"}
    ]
    dependencies = [
        "requests>=2.28.0",
        "click>=8.0.0",
    ]
    requires-python = ">=3.8"
    
    [project.optional-dependencies]
    dev = [
        "pytest>=7.0.0",
        "black>=22.0.0",
        "flake8>=5.0.0",
    ]
    docs = [
        "sphinx>=5.0.0",
        "sphinx-rtd-theme>=1.0.0",
    ]
    
    [tool.uv]
    dev-dependencies = [
        "pytest-cov>=4.0.0",
    ]
    
    [build-system]
    requires = ["hatchling"]
    build-backend = "hatchling.build"
    INI

    Project Configuration Structure

    graph TD
        A[pyproject.toml] --> B[project section]
        A --> C[tool.uv section]
        A --> D[build-system section]
    
        B --> E[Basic metadata]
        B --> F[Dependencies]
        B --> G[Optional dependencies]
    
        C --> H[uv-specific config]
        C --> I[Development dependencies]
    
        D --> J[Build requirements]
        D --> K[Build backend]
    
        E --> L[name, version, description]
        F --> M[Runtime requirements]
        G --> N[Feature groups]
    
        style A fill:#fff3e0
        style B fill:#e8f5e8
        style C fill:#e3f2fd
        style D fill:#fce4ec

    Lock Files (uv.lock)

    The uv.lock file contains exact versions of all dependencies:

    version = 1
    requires-python = ">=3.8"
    
    [[package]]
    name = "certifi"
    version = "2023.7.22"
    source = { registry = "https://pypi.org/simple" }
    sdist = { url = "https://files.pythonhosted.org/packages/98/98/c2ff18671db109c9f10ed27f5ef610ae05b73bd876664139cf95bd1429aa/certifi-2023.7.22.tar.gz", hash = "sha256:539cc1d13202e33ca466e88b2807e29f4c13049d6d87031a3c110744495cb082" }
    wheels = [
        { url = "https://files.pythonhosted.org/packages/88/5f/e351af9a41f866ac3f1fac4ca0613908d9a41741cfcf2228f4e80058d3...certifi-2023.7.22-py3-none-any.whl", hash = "sha256:92d6037539857d8206b8f6ae472e8b77db8058fec5937a1ef3f54304089edbb9" },
    ]
    
    dependencies = [
        { name = "requests" },
    ]
    INI

    Workspace Configuration

    For multi-package projects, use workspace configuration:

    [tool.uv.workspace]
    members = [
        "packages/*",
        "apps/web",
        "apps/api",
    ]
    
    [tool.uv.workspace.dependencies]
    shared-utils = { path = "packages/shared-utils" }
    INI

    Workspace Structure

    graph TD
        A[Workspace Root] --> B[pyproject.toml]
        A --> C[packages/]
        A --> D[apps/]
        A --> E[uv.lock]
    
        C --> F[shared-utils/]
        C --> G[common-types/]
    
        D --> H[web/]
        D --> I[api/]
    
        F --> J[pyproject.toml]
        G --> K[pyproject.toml]
        H --> L[pyproject.toml]
        I --> M[pyproject.toml]
    
        style A fill:#1976d2,color:#fff
        style B fill:#4caf50,color:#fff
        style E fill:#ff9800,color:#fff

    10. Advanced Features

    Tool Management

    uv can manage external tools without polluting your project environment:

    # Install a tool globally
    uv tool install black
    
    # Run a tool without installing
    uv tool run ruff check .
    
    # List installed tools
    uv tool list
    
    # Upgrade a tool
    uv tool upgrade black
    
    # Uninstall a tool
    uv tool uninstall black
    Bash

    Tool Isolation

    graph TD
        A[System] --> B[uv Tool Environment]
        A --> C[Project Environment]
        A --> D[Global Environment]
    
        B --> E[black]
        B --> F[ruff]
        B --> G[mypy]
    
        C --> H[Project Dependencies]
        C --> I[Dev Dependencies]
    
        D --> J[System Packages]
    
        style B fill:#e1f5fe
        style C fill:#f3e5f5
        style D fill:#fff3e0

    Script Management

    Inline Scripts

    Create executable Python scripts with dependencies:

    #!/usr/bin/env uv run
    # /// script
    # requires-python = ">=3.8"
    # dependencies = [
    #     "requests",
    #     "click",
    # ]
    # ///
    
    import requests
    import click
    
    @click.command()
    @click.argument("url")
    def fetch(url):
        """Fetch and display URL content."""
        response = requests.get(url)
        click.echo(response.text[:200])
    
    if __name__ == "__main__":
        fetch()
    Python

    Run with:

    uv run script.py https://httpbin.org/json
    Bash

    Publishing Packages

    Building Packages

    # Build wheel and sdist
    uv build
    
    # Build only wheel
    uv build --wheel
    
    # Build only sdist
    uv build --sdist
    Bash

    Publishing Workflow

    sequenceDiagram
        participant Dev as Developer
        participant uv as uv CLI
        participant Build as Build System
        participant PyPI as PyPI
    
        Dev->>uv: uv build
        uv->>Build: Invoke build backend
        Build->>uv: Generate artifacts
        uv->>Dev: dist/ created
    
        Dev->>uv: uv publish
        uv->>PyPI: Upload artifacts
        PyPI->>uv: Confirmation
        uv->>Dev: Published successfully

    Advanced Dependency Resolution

    Resolution Strategies

    # Use highest version resolution
    uv add --resolution highest package
    
    # Use lowest version resolution  
    uv add --resolution lowest package
    
    # Preview resolution without installing
    uv add --dry-run package
    Bash

    Dependency Override

    In pyproject.toml:

    [tool.uv]
    override-dependencies = [
        "numpy==1.24.0",  # Force specific version
    ]
    
    [[tool.uv.index]]
    name = "pytorch"
    url = "https://download.pytorch.org/whl/cpu"
    explicit = true
    INI

    Caching and Performance

    Cache Management

    # Show cache information
    uv cache info
    
    # Clean cache
    uv cache clean
    
    # Clean specific package from cache
    uv cache clean requests
    Bash

    Cache Architecture

    graph TD
        A[uv Cache] --> B[Package Cache]
        A --> C[Python Cache]
        A --> D[Tool Cache]
    
        B --> E[Wheels]
        B --> F[Source Distributions]
        B --> G[Metadata]
    
        C --> H[Python Interpreters]
        C --> I[Standard Library]
    
        D --> J[Installed Tools]
        D --> K[Tool Environments]
    
        style A fill:#1976d2,color:#fff
        style B fill:#4caf50,color:#fff
        style C fill:#ff9800,color:#fff
        style D fill:#9c27b0,color:#fff

    11. Performance and Optimization

    Speed Comparisons

    Installation Speed Benchmark

    xychart-beta
        title "Package Installation Speed Comparison"
        x-axis [pip, poetry, conda, uv]
        y-axis "Time (seconds)" 0 --> 50
        bar [45, 30, 25, 3]

    Memory Usage

    xychart-beta
        title "Memory Usage During Installation"
        x-axis [pip, poetry, conda, uv]
        y-axis "Memory (MB)" 0 --> 500
        bar [400, 350, 450, 150]

    Optimization Strategies

    1. Use the Cache Effectively

    # Pre-populate cache for CI
    uv cache sync
    
    # Use cache in CI/CD
    uv install --cache-dir /cache/uv
    Bash

    2. Optimize pyproject.toml

    [tool.uv]
    # Use fewer network requests
    index-strategy = "unsafe-first-match"
    
    # Compile from source less often
    compile-bytecode = false
    
    # Use specific indexes for faster resolution
    [[tool.uv.index]]
    name = "pytorch"
    url = "https://download.pytorch.org/whl/cpu"
    INI

    3. Parallel Installation

    uv automatically parallelizes package installation:

    graph TD
        A[Package List] --> B[Dependency Graph]
        B --> C[Parallel Worker 1]
        B --> D[Parallel Worker 2]
        B --> E[Parallel Worker 3]
        B --> F[Parallel Worker N]
    
        C --> G[Install Package A]
        D --> H[Install Package B]
        E --> I[Install Package C]
        F --> J[Install Package ...]
    
        G --> K[Completion]
        H --> K
        I --> K
        J --> K
    
        style A fill:#1976d2,color:#fff
        style K fill:#4caf50,color:#fff

    Performance Monitoring

    Profiling Installation

    # Verbose output for debugging
    uv add --verbose package
    
    # Show resolution process
    uv lock --upgrade --verbose
    
    # Time operations
    time uv add package
    Bash

    Cache Statistics

    # Show cache hit rates
    uv cache info --verbose
    
    # Monitor cache size
    du -sh ~/.cache/uv
    Bash

    12. Troubleshooting

    Common Issues and Solutions

    1. Resolution Conflicts

    Problem: Package version conflicts Solution: Use resolution strategies

    # Try lowest compatible versions
    uv add --resolution lowest conflicting-package
    
    # Override specific dependencies
    # In pyproject.toml:
    [tool.uv]
    override-dependencies = ["problematic-package==1.0.0"]
    Bash

    2. Python Version Issues

    Problem: Python version not found Solution: Install or specify different version

    # Install required Python version
    uv python install 3.11
    
    # Use different version
    uv add --python 3.10 package
    Bash

    3. Network and Proxy Issues

    Problem: Cannot reach PyPI Solution: Configure network settings

    # Use different index
    uv add --index-url https://pypi.org/simple/ package
    
    # Configure proxy
    export HTTPS_PROXY=http://proxy.company.com:8080
    uv add package
    Bash

    Troubleshooting Workflow

    flowchart TD
        A[Issue Encountered] --> B{Type of Issue?}
    
        B -->|Resolution| C[Check Dependencies]
        B -->|Network| D[Check Connectivity]
        B -->|Python| E[Check Python Version]
        B -->|Permission| F[Check File Permissions]
    
        C --> G[Use --resolution flag]
        C --> H[Override dependencies]
    
        D --> I[Configure proxy]
        D --> J[Use different index]
    
        E --> K[Install Python version]
        E --> L[Use --python flag]
    
        F --> M[Fix permissions]
        F --> N[Use --user flag]
    
        G --> O[Test Solution]
        H --> O
        I --> O
        J --> O
        K --> O
        L --> O
        M --> O
        N --> O
    
        O --> P{Resolved?}
        P -->|Yes| Q[Success]
        P -->|No| R[Advanced Debugging]
    
        style Q fill:#c8e6c9
        style R fill:#ffcdd2

    Debug Commands

    # Verbose output
    uv --verbose add package
    
    # Show resolution tree
    uv tree
    
    # Check environment
    uv pip check
    
    # Show configuration
    uv config
    
    # Validate lock file
    uv lock --check
    Bash

    Log Analysis

    Understanding uv Logs

    # Enable debug logging
    UV_LOG_LEVEL=debug uv add package
    
    # Log to file
    uv add package 2> uv.log
    Bash

    Common Log Patterns

    graph TD
        A[uv Log Entry] --> B[Timestamp]
        A --> C[Log Level]
        A --> D[Component]
        A --> E[Message]
    
        C --> F[TRACE]
        C --> G[DEBUG]
        C --> H[INFO]
        C --> I[WARN]
        C --> J[ERROR]
    
        D --> K[resolver]
        D --> L[installer]
        D --> M[cache]
        D --> N[client]
    
        style A fill:#1976d2,color:#fff
        style J fill:#f44336,color:#fff
        style I fill:#ff9800,color:#fff

    13. Best Practices

    Project Organization

    my-project/
    β”œβ”€β”€ pyproject.toml          # Project configuration
    β”œβ”€β”€ uv.lock                 # Dependency lock file
    β”œβ”€β”€ .python-version         # Python version pin
    β”œβ”€β”€ README.md               # Documentation
    β”œβ”€β”€ src/                    # Source code
    β”‚   └── my_project/
    β”‚       β”œβ”€β”€ __init__.py
    β”‚       └── main.py
    β”œβ”€β”€ tests/                  # Test files
    β”‚   β”œβ”€β”€ __init__.py
    β”‚   └── test_main.py
    β”œβ”€β”€ docs/                   # Documentation
    └── scripts/                # Utility scripts
    Bash

    Configuration Management

    # pyproject.toml best practices
    [project]
    name = "my-project"
    version = "0.1.0"
    description = "Clear, concise description"
    readme = "README.md"
    license = {text = "MIT"}
    authors = [
        {name = "Author Name", email = "author@example.com"}
    ]
    classifiers = [
        "Development Status :: 4 - Beta",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "Programming Language :: Python :: 3.11",
    ]
    requires-python = ">=3.8"
    dependencies = [
        "requests>=2.28.0",
        "click>=8.0.0",
    ]
    
    [project.optional-dependencies]
    dev = [
        "pytest>=7.0.0",
        "pytest-cov>=4.0.0",
        "black>=22.0.0",
        "ruff>=0.1.0",
        "mypy>=1.0.0",
    ]
    docs = [
        "sphinx>=5.0.0",
        "sphinx-rtd-theme>=1.0.0",
    ]
    
    [project.scripts]
    my-cli = "my_project.cli:main"
    
    [tool.uv]
    dev-dependencies = [
        "pre-commit>=3.0.0",
    ]
    
    [tool.black]
    line-length = 88
    target-version = ['py38']
    
    [tool.ruff]
    line-length = 88
    target-version = "py38"
    
    [tool.mypy]
    python_version = "3.8"
    strict = true
    INI

    Dependency Management Best Practices

    1. Use Version Constraints Wisely

    graph TD
        A[Version Constraint Strategy] --> B[Pin Major Version]
        A --> C[Allow Minor Updates]
        A --> D[Be Cautious with Pre-releases]
    
        B --> E[">=1.0.0,<2.0.0"]
        C --> F["~=1.4.0"]
        D --> G[">=1.0.0"]
    
        style A fill:#1976d2,color:#fff
        style B fill:#4caf50,color:#fff
        style C fill:#ff9800,color:#fff
        style D fill:#f44336,color:#fff

    2. Organize Dependencies by Purpose

    # Core runtime dependencies
    dependencies = [
        "fastapi>=0.100.0",
        "uvicorn>=0.23.0",
        "pydantic>=2.0.0",
    ]
    
    # Development tools
    [project.optional-dependencies]
    dev = [
        "pytest>=7.0.0",
        "black>=22.0.0",
        "ruff>=0.1.0",
    ]
    
    # Testing dependencies
    test = [
        "pytest>=7.0.0",
        "pytest-asyncio>=0.21.0",
        "httpx>=0.24.0",
    ]
    
    # Documentation
    docs = [
        "mkdocs>=1.5.0",
        "mkdocs-material>=9.0.0",
    ]
    INI

    3. Lock File Management

    # Update lock file regularly
    uv lock --upgrade
    
    # Update specific package
    uv lock --upgrade-package requests
    
    # Check for outdated packages
    uv pip list --outdated
    Bash

    Development Workflow

    gitGraph
        commit id: "Initial commit"
    
        branch feature
        checkout feature
        commit id: "Add feature"
        commit id: "Update dependencies"
        commit id: "Add tests"
    
        checkout main
        commit id: "Update lock file"
    
        merge feature id: "Merge feature"
    
        commit id: "Release v1.0.0"

    Pre-commit Hooks

    Create .pre-commit-config.yaml:

    repos:
      - repo: https://github.com/psf/black
        rev: 23.7.0
        hooks:
          - id: black
            language_version: python3.11
    
      - repo: https://github.com/charliermarsh/ruff-pre-commit
        rev: v0.0.287
        hooks:
          - id: ruff
            args: [--fix, --exit-non-zero-on-fix]
    
      - repo: https://github.com/pre-commit/mirrors-mypy
        rev: v1.5.1
        hooks:
          - id: mypy
            additional_dependencies: [types-requests]
    YAML

    CI/CD Integration

    GitHub Actions Example

    name: CI
    
    on: [push, pull_request]
    
    jobs:
      test:
        runs-on: ubuntu-latest
        strategy:
          matrix:
            python-version: ["3.8", "3.9", "3.10", "3.11"]
    
        steps:
        - uses: actions/checkout@v4
    
        - name: Install uv
          uses: astral-sh/setup-uv@v1
          with:
            version: "latest"
    
        - name: Set up Python ${{ matrix.python-version }}
          run: uv python install ${{ matrix.python-version }}
    
        - name: Install dependencies
          run: uv sync --all-extras --dev
    
        - name: Run tests
          run: uv run pytest
    
        - name: Run linting
          run: |
            uv run black --check .
            uv run ruff check .
            uv run mypy .
    YAML

    Security Best Practices

    1. Dependency Security

    # Audit dependencies for vulnerabilities
    uv pip audit
    
    # Use trusted sources
    uv add --trusted-host pypi.org package
    
    # Verify checksums
    uv add --require-hashes package
    Bash

    2. Environment Isolation

    graph TD
        A[Security Layers] --> B[Virtual Environments]
        A --> C[Tool Isolation]
        A --> D[Dependency Auditing]
        A --> E[Source Verification]
    
        B --> F[Project Isolation]
        C --> G[Tool Environments]
        D --> H[Vulnerability Scanning]
        E --> I[Package Verification]
    
        style A fill:#1976d2,color:#fff
        style B fill:#4caf50,color:#fff
        style C fill:#ff9800,color:#fff
        style D fill:#f44336,color:#fff
        style E fill:#9c27b0,color:#fff

    14. Migration Guide

    Migrating from pip

    Basic pip to uv Migration

    Before (pip):

    pip install requests
    pip install -r requirements.txt
    pip freeze > requirements.txt
    Bash

    After (uv):

    uv add requests
    uv add -r requirements.txt
    uv pip freeze > requirements.txt
    Bash

    Migration Steps

    flowchart TD
        A[Start Migration] --> B[Install uv]
        B --> C[Create pyproject.toml]
        C --> D[Import requirements.txt]
        D --> E[Generate lock file]
        E --> F[Test installation]
        F --> G[Update CI/CD]
        G --> H[Migration Complete]
    
        style A fill:#fff3e0
        style H fill:#c8e6c9

    Migrating from Poetry

    Converting pyproject.toml

    Poetry format:

    [tool.poetry]
    name = "my-project"
    version = "0.1.0"
    description = ""
    authors = ["Author <author@example.com>"]
    
    [tool.poetry.dependencies]
    python = "^3.8"
    requests = "^2.28.0"
    
    [tool.poetry.group.dev.dependencies]
    pytest = "^7.0.0"
    INI

    uv format:

    [project]
    name = "my-project"
    version = "0.1.0"
    description = ""
    authors = [{name = "Author", email = "author@example.com"}]
    requires-python = ">=3.8"
    dependencies = [
        "requests>=2.28.0,<3.0.0",
    ]
    
    [project.optional-dependencies]
    dev = [
        "pytest>=7.0.0,<8.0.0",
    ]
    INI

    Automated Migration

    # Convert poetry.lock to uv.lock
    uv add $(poetry export --format=requirements.txt --output=-)
    
    # Or use migration tool
    uv init --from-poetry
    Bash

    Migrating from Pipenv

    Pipfile to pyproject.toml

    Pipfile:

    [[source]]
    url = "https://pypi.org/simple"
    verify_ssl = true
    name = "pypi"
    
    [packages]
    requests = "*"
    django = ">=4.0,<5.0"
    
    [dev-packages]
    pytest = "*"
    
    [requires]
    python_version = "3.11"
    INI

    Equivalent uv configuration:

    [project]
    requires-python = ">=3.11"
    dependencies = [
        "requests",
        "django>=4.0,<5.0",
    ]
    
    [project.optional-dependencies]
    dev = [
        "pytest",
    ]
    INI

    Migration Checklist

    graph TD
        A[Migration Checklist] --> B[βœ“ Install uv]
        A --> C[βœ“ Convert configuration]
        A --> D[βœ“ Import dependencies]
        A --> E[βœ“ Update scripts]
        A --> F[βœ“ Update CI/CD]
        A --> G[βœ“ Update documentation]
        A --> H[βœ“ Train team]
    
        style A fill:#1976d2,color:#fff
        style B fill:#4caf50,color:#fff
        style C fill:#4caf50,color:#fff
        style D fill:#4caf50,color:#fff
        style E fill:#4caf50,color:#fff
        style F fill:#4caf50,color:#fff
        style G fill:#4caf50,color:#fff
        style H fill:#4caf50,color:#fff

    15. Expert Tips and Tricks

    Advanced Configuration

    Custom Indexes and Repositories

    [tool.uv]
    # Multiple package indexes
    [[tool.uv.index]]
    name = "pytorch"
    url = "https://download.pytorch.org/whl/cpu"
    explicit = true
    
    [[tool.uv.index]]
    name = "private"
    url = "https://pypi.company.com/simple"
    default = true
    
    # Index priority
    index-strategy = "first-index"
    
    # Source distributions preferences
    no-build = ["numpy", "scipy"]  # Don't build these from source
    build = ["custom-package"]     # Always build from source
    INI

    Environment Variables

    # Configuration via environment variables
    export UV_INDEX_URL=https://pypi.org/simple
    export UV_EXTRA_INDEX_URL=https://download.pytorch.org/whl/cpu
    export UV_NO_CACHE=1
    export UV_CACHE_DIR=/custom/cache/path
    export UV_PYTHON=3.11
    Bash

    Performance Optimization

    Parallel Processing Tuning

    [tool.uv]
    # Adjust concurrent downloads
    concurrent-downloads = 50
    
    # Adjust concurrent builds
    concurrent-builds = 4
    
    # Network timeout settings
    timeout = 30
    INI

    Cache Optimization

    # Pre-warm cache for better performance
    uv cache warm
    
    # Clean cache periodically
    uv cache clean --older-than=30d
    
    # Cache statistics
    uv cache info --stats
    Bash

    Advanced Scripting

    Dynamic Dependency Scripts

    #!/usr/bin/env uv run
    # /// script
    # requires-python = ">=3.8"
    # dependencies = [
    #     "httpx",
    #     "rich",
    #     "typer",
    # ]
    # ///
    
    import asyncio
    import httpx
    from rich.console import Console
    from rich.progress import Progress
    import typer
    
    console = Console()
    
    async def fetch_urls(urls: list[str]) -> None:
        """Fetch multiple URLs concurrently."""
        async with httpx.AsyncClient() as client:
            with Progress() as progress:
                task = progress.add_task("Fetching...", total=len(urls))
    
                async def fetch_one(url: str) -> None:
                    response = await client.get(url)
                    console.print(f"[green]{url}[/green]: {response.status_code}")
                    progress.advance(task)
    
                await asyncio.gather(*(fetch_one(url) for url in urls))
    
    def main(urls: list[str]) -> None:
        """Main CLI entry point."""
        asyncio.run(fetch_urls(urls))
    
    if __name__ == "__main__":
        typer.run(main)
    Python

    Workspace Management

    Multi-package Workspace

    # Root pyproject.toml
    [tool.uv.workspace]
    members = [
        "packages/*",
        "services/*",
    ]
    
    # Shared dependencies across workspace
    [tool.uv.workspace.dependencies]
    pytest = ">=7.0.0"
    mypy = ">=1.0.0"
    
    # Package-specific overrides
    [tool.uv.workspace.package-overrides]
    "my-package" = { python = ">=3.10" }
    INI

    Workspace Dependency Graph

    graph TD
        A[Workspace Root] --> B[Package A]
        A --> C[Package B]
        A --> D[Service X]
        A --> E[Service Y]
    
        B --> F[Shared Utils]
        C --> F
        D --> B
        D --> C
        E --> C
    
        F --> G[Common Types]
    
        style A fill:#1976d2,color:#fff
        style F fill:#4caf50,color:#fff
        style G fill:#ff9800,color:#fff

    Custom Tools Integration

    Creating uv Tools

    # tool_template.py
    #!/usr/bin/env python3
    """Custom uv tool template."""
    
    import subprocess
    import sys
    from pathlib import Path
    
    def run_uv_command(args: list[str]) -> int:
        """Run uv command with custom logic."""
        cmd = ["uv"] + args
    
        # Custom pre-processing
        if "--my-flag" in args:
            args.remove("--my-flag")
            print("Custom flag detected!")
    
        # Run uv command
        result = subprocess.run(cmd, capture_output=False)
    
        # Custom post-processing
        if result.returncode == 0:
            print("βœ… Command succeeded!")
    
        return result.returncode
    
    if __name__ == "__main__":
        sys.exit(run_uv_command(sys.argv[1:]))
    Python

    Monitoring and Metrics

    Performance Monitoring

    #!/usr/bin/env uv run
    # /// script
    # dependencies = ["psutil", "rich"]
    # ///
    
    import time
    import psutil
    from rich.console import Console
    from rich.table import Table
    from rich.live import Live
    
    def monitor_uv_process():
        """Monitor uv process performance."""
        console = Console()
    
        def make_table():
            table = Table()
            table.add_column("Metric")
            table.add_column("Value")
    
            for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_info']):
                if 'uv' in proc.info['name']:
                    table.add_row("PID", str(proc.info['pid']))
                    table.add_row("CPU %", f"{proc.info['cpu_percent']:.1f}%")
                    table.add_row("Memory", f"{proc.info['memory_info'].rss / 1024 / 1024:.1f} MB")
    
            return table
    
        with Live(make_table(), refresh_per_second=1) as live:
            while True:
                time.sleep(1)
                live.update(make_table())
    
    if __name__ == "__main__":
        monitor_uv_process()
    Python

    Integration Patterns

    Docker Integration

    # Dockerfile optimized for uv
    FROM python:3.11-slim
    
    # Install uv
    COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv
    
    # Copy dependency files
    COPY pyproject.toml uv.lock ./
    
    # Install dependencies
    RUN uv sync --frozen --no-cache
    
    # Copy application code
    COPY . .
    
    # Run application
    CMD ["uv", "run", "python", "-m", "myapp"]
    Dockerfile

    IDE Integration

    VS Code settings.json:

    {
        "python.defaultInterpreterPath": "./.venv/bin/python",
        "python.terminal.activateEnvironment": false,
        "python.formatting.provider": "black",
        "python.linting.enabled": true,
        "python.linting.ruffEnabled": true,
        "terminal.integrated.env.linux": {
            "UV_PROJECT_ENVIRONMENT": ".venv"
        }
    }
    JSON

    Debugging and Profiling

    Advanced Debugging

    # Debug dependency resolution
    UV_LOG_LEVEL=trace uv add package 2> resolution.log
    
    # Profile installation
    UV_PROFILING=1 uv add package
    
    # Memory debugging
    UV_DEBUG_MEMORY=1 uv sync
    INI

    Custom Debug Tools

    #!/usr/bin/env uv run
    # /// script
    # dependencies = ["click", "tomlkit"]
    # ///
    
    import click
    import tomlkit
    from pathlib import Path
    
    @click.command()
    @click.option("--project", default=".", help="Project directory")
    def debug_project(project: str):
        """Debug uv project configuration."""
        project_path = Path(project)
        pyproject_path = project_path / "pyproject.toml"
        lock_path = project_path / "uv.lock"
    
        if pyproject_path.exists():
            with open(pyproject_path) as f:
                config = tomlkit.parse(f.read())
    
            click.echo("πŸ“‹ Project Configuration:")
            click.echo(f"  Name: {config.get('project', {}).get('name', 'Unknown')}")
            click.echo(f"  Python: {config.get('project', {}).get('requires-python', 'Not specified')}")
    
            deps = config.get('project', {}).get('dependencies', [])
            click.echo(f"  Dependencies: {len(deps)}")
    
            if lock_path.exists():
                click.echo("πŸ”’ Lock file: Present")
            else:
                click.echo("❌ Lock file: Missing")
        else:
            click.echo("❌ No pyproject.toml found")
    
    if __name__ == "__main__":
        debug_project()
    Python

    18. Quick Reference

    Essential Commands Cheat Sheet

    Project Management

    # Initialize new project
    uv init project-name
    
    # Add dependencies
    uv add package-name
    uv add "package>=1.0,<2.0"
    uv add --dev pytest
    uv add --optional docs sphinx
    
    # Remove dependencies
    uv remove package-name
    uv remove --dev pytest
    
    # Sync environment with lock file
    uv sync
    uv sync --dev
    uv sync --no-dev
    Bash

    Environment Management

    # Create virtual environment
    uv venv
    uv venv --python 3.11
    uv venv my-env
    
    # Run commands in environment
    uv run python script.py
    uv run --env my-env python script.py
    
    # Show environment info
    uv venv --show-path
    Bash

    Python Version Management

    # List Python versions
    uv python list
    uv python list --installed
    
    # Install Python version
    uv python install 3.11
    uv python install 3.11.5
    
    # Pin Python version
    uv python pin 3.11
    Bash

    Tool Management

    # Install global tool
    uv tool install black
    
    # Run tool without installing
    uv tool run black script.py
    uv tool run --from black==23.7.0 black .
    
    # List installed tools
    uv tool list
    
    # Upgrade tool
    uv tool upgrade black
    Bash

    Package Information

    # List installed packages
    uv pip list
    uv pip list --outdated
    
    # Show package info
    uv pip show package-name
    
    # Check for security vulnerabilities
    uv pip audit
    Bash

    Configuration Quick Reference

    pyproject.toml Template

    [project]
    name = "my-project"
    version = "0.1.0"
    description = "Project description"
    readme = "README.md"
    authors = [{name = "Author", email = "author@example.com"}]
    requires-python = ">=3.8"
    dependencies = [
        "requests>=2.28.0",
    ]
    
    [project.optional-dependencies]
    dev = ["pytest>=7.0.0", "black>=22.0.0"]
    docs = ["sphinx>=5.0.0"]
    
    [project.scripts]
    my-cli = "my_project.cli:main"
    
    [tool.uv]
    dev-dependencies = ["pre-commit>=3.0.0"]
    
    [build-system]
    requires = ["hatchling"]
    build-backend = "hatchling.build"
    INI

    Global Configuration

    # ~/.config/uv/uv.toml (Unix) or %APPDATA%\uv\uv.toml (Windows)
    [tool.uv]
    python = "3.11"
    cache-dir = "~/.cache/uv"
    index-url = "https://pypi.org/simple"
    concurrent-downloads = 10
    timeout = 30
    INI

    Common Workflows

    Starting a New Project

    # 1. Create project
    uv init my-project
    cd my-project
    
    # 2. Add dependencies
    uv add requests click
    
    # 3. Add dev dependencies
    uv add --dev pytest black ruff
    
    # 4. Create main script
    echo 'print("Hello, uv!")' > src/my_project/main.py
    
    # 5. Run the script
    uv run python src/my_project/main.py
    Bash

    Working with Existing Project

    # 1. Clone repository
    git clone https://github.com/user/project.git
    cd project
    
    # 2. Sync dependencies
    uv sync
    
    # 3. Run tests
    uv run pytest
    
    # 4. Add new dependency
    uv add new-package
    
    # 5. Update lock file
    uv lock
    Bash

    19. Expert Tips & Tricks

    Performance Optimization

    1. Cache Management

    # Pre-warm cache for CI
    uv cache warm
    
    # Clean old cache entries
    uv cache clean --older-than=30d
    
    # Show cache statistics
    uv cache info --stats
    
    # Use custom cache location
    UV_CACHE_DIR=/custom/path uv add package
    Bash

    2. Parallel Operations

    # pyproject.toml
    [tool.uv]
    concurrent-downloads = 50  # Increase for faster downloads
    concurrent-builds = 8      # Adjust based on CPU cores
    INI

    3. Smart Resolution Strategies

    # Use lowest compatible versions
    uv add --resolution lowest package
    
    # Preview changes without installing
    uv add --dry-run package
    
    # Upgrade specific package
    uv lock --upgrade-package requests
    Bash

    Advanced Configuration

    Custom Indexes

    [tool.uv]
    [[tool.uv.index]]
    name = "pytorch"
    url = "https://download.pytorch.org/whl/cpu"
    explicit = true
    
    [[tool.uv.index]]
    name = "private"
    url = "https://pypi.company.com/simple"
    default = true
    INI

    Environment Variables

    # Development shortcuts
    export UV_PROJECT_ENVIRONMENT=".venv"
    export UV_PYTHON="3.11"
    export UV_INDEX_URL="https://pypi.org/simple"
    
    # CI/CD optimizations
    export UV_NO_CACHE=1           # Disable cache
    export UV_CACHE_DIR="/cache"   # Custom cache location
    export UV_COMPILE_BYTECODE=0   # Skip bytecode compilation
    Bash

    Scripting and Automation

    Self-Contained Scripts

    #!/usr/bin/env uv run
    # /// script
    # requires-python = ">=3.8"
    # dependencies = [
    #     "httpx",
    #     "rich",
    # ]
    # ///
    
    import asyncio
    import httpx
    from rich.console import Console
    
    console = Console()
    
    async def fetch_data(url: str) -> None:
        async with httpx.AsyncClient() as client:
            response = await client.get(url)
            console.print(f"[green]{url}[/green]: {response.status_code}")
    
    if __name__ == "__main__":
        asyncio.run(fetch_data("https://httpbin.org/json"))
    Python

    Custom Workspace Tools

    # workspace-tool.py - Custom workspace management
    #!/usr/bin/env uv run
    # /// script
    # dependencies = ["click", "tomlkit", "rich"]
    # ///
    
    import click
    from pathlib import Path
    from rich.console import Console
    
    @click.group()
    def cli():
        """Custom workspace management tool."""
        pass
    
    @cli.command()
    def status():
        """Show workspace status."""
        console = Console()
    
        pyproject = Path("pyproject.toml")
        if pyproject.exists():
            console.print("βœ… Project configured")
        else:
            console.print("❌ No pyproject.toml found")
    
        lockfile = Path("uv.lock")
        if lockfile.exists():
            console.print("βœ… Dependencies locked")
        else:
            console.print("⚠️ No lock file found")
    
    if __name__ == "__main__":
        cli()
    Python

    Integration Patterns

    Docker Optimization

    # Multi-stage build for smaller images
    FROM python:3.11-slim as builder
    
    # Install uv
    COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv
    
    # Copy dependency files
    COPY pyproject.toml uv.lock ./
    
    # Install dependencies to a virtual environment
    RUN uv sync --frozen --no-cache --no-dev
    
    FROM python:3.11-slim
    
    # Copy virtual environment
    COPY --from=builder /.venv /.venv
    
    # Ensure venv is in PATH
    ENV PATH="/.venv/bin:$PATH"
    
    # Copy application
    COPY . .
    
    CMD ["python", "-m", "myapp"]
    Dockerfile

    GitHub Actions Optimization

    name: CI with uv caching
    
    on: [push, pull_request]
    
    jobs:
      test:
        runs-on: ubuntu-latest
    
        steps:
        - uses: actions/checkout@v4
    
        - name: Set up uv
          uses: astral-sh/setup-uv@v1
          with:
            enable-cache: true
            cache-dependency-glob: "**/uv.lock"
    
        - name: Install dependencies
          run: uv sync --all-extras --dev
    
        - name: Run tests
          run: uv run pytest --cov
    YAML

    Debugging and Troubleshooting

    Verbose Debugging

    # Maximum verbosity
    UV_LOG_LEVEL=trace uv add package 2> debug.log
    
    # Profile resolution performance
    UV_PROFILING=1 uv lock
    
    # Debug memory usage
    UV_DEBUG_MEMORY=1 uv sync
    Bash

    Custom Debug Script

    #!/usr/bin/env uv run
    # /// script
    # dependencies = ["click", "tomlkit", "rich-click"]
    # ///
    
    import click
    from pathlib import Path
    from rich import print as rprint
    
    @click.command()
    @click.option("--project", default=".", help="Project directory")
    def debug_uv(project: str):
        """Debug uv project configuration."""
        project_path = Path(project).resolve()
    
        rprint(f"[bold blue]Debugging project:[/bold blue] {project_path}")
    
        # Check project files
        files_to_check = ["pyproject.toml", "uv.lock", ".python-version"]
        for file in files_to_check:
            file_path = project_path / file
            if file_path.exists():
                rprint(f"βœ… {file}: Found")
            else:
                rprint(f"❌ {file}: Missing")
    
        # Check virtual environment
        venv_path = project_path / ".venv"
        if venv_path.exists():
            rprint(f"βœ… Virtual environment: {venv_path}")
        else:
            rprint("❌ Virtual environment: Not found")
    
    if __name__ == "__main__":
        debug_uv()
    Python

    20. Hands-on Labs

    Lab 1: Building a CLI Application

    Objective: Create a weather CLI app using uv

    Time: 30 minutes

    Step 1: Initialize Project

    uv init weather-cli
    cd weather-cli
    Bash

    Step 2: Add Dependencies

    uv add click requests rich
    uv add --dev pytest pytest-mock
    Bash

    Step 3: Create the CLI

    Create src/weather_cli/main.py:

    import click
    import requests
    from rich.console import Console
    from rich.table import Table
    
    console = Console()
    
    @click.command()
    @click.option("--city", prompt="City name", help="City to get weather for")
    @click.option("--units", default="metric", help="Temperature units")
    def weather(city: str, units: str):
        """Get weather information for a city."""
        try:
            # Using OpenWeatherMap API (free tier)
            api_key = "your_api_key_here"  # Get from openweathermap.org
            url = f"http://api.openweathermap.org/data/2.5/weather"
            params = {"q": city, "appid": api_key, "units": units}
    
            response = requests.get(url, params=params)
            response.raise_for_status()
            data = response.json()
    
            # Create weather table
            table = Table(title=f"Weather in {city.title()}")
            table.add_column("Metric", style="cyan")
            table.add_column("Value", style="magenta")
    
            table.add_row("Temperature", f"{data['main']['temp']}Β°C")
            table.add_row("Feels like", f"{data['main']['feels_like']}Β°C")
            table.add_row("Humidity", f"{data['main']['humidity']}%")
            table.add_row("Description", data['weather'][0]['description'].title())
    
            console.print(table)
    
        except requests.RequestException as e:
            console.print(f"[red]Error fetching weather data: {e}[/red]")
        except KeyError as e:
            console.print(f"[red]Unexpected response format: {e}[/red]")
    
    if __name__ == "__main__":
        weather()
    Python

    Step 4: Configure Entry Point

    Update pyproject.toml:

    [project.scripts]
    weather = "weather_cli.main:weather"
    INI

    Step 5: Run the Application

    uv run weather --city "London"
    Bash

    Lab 2: Data Analysis Pipeline

    Objective: Create a data analysis project with Jupyter integration

    Time: 45 minutes

    Step 1: Initialize Data Project

    uv init data-analysis
    cd data-analysis
    Bash

    Step 2: Add Data Science Dependencies

    uv add pandas numpy matplotlib seaborn jupyter
    uv add --dev pytest ipykernel
    Bash

    Step 3: Create Analysis Script

    Create src/data_analysis/analyzer.py:

    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    from pathlib import Path
    
    class DataAnalyzer:
        def __init__(self, data_path: str):
            self.data_path = Path(data_path)
            self.df = None
    
        def load_data(self):
            """Load data from CSV file."""
            if self.data_path.suffix == '.csv':
                self.df = pd.read_csv(self.data_path)
            else:
                raise ValueError("Only CSV files supported")
            return self.df
    
        def basic_stats(self):
            """Generate basic statistics."""
            if self.df is None:
                raise ValueError("Data not loaded")
    
            stats = {
                'shape': self.df.shape,
                'columns': list(self.df.columns),
                'dtypes': self.df.dtypes.to_dict(),
                'missing': self.df.isnull().sum().to_dict(),
                'numeric_summary': self.df.describe().to_dict()
            }
            return stats
    
        def create_plots(self, output_dir: str = "plots"):
            """Create visualization plots."""
            output_path = Path(output_dir)
            output_path.mkdir(exist_ok=True)
    
            # Correlation heatmap for numeric columns
            numeric_cols = self.df.select_dtypes(include=['number']).columns
            if len(numeric_cols) > 1:
                plt.figure(figsize=(10, 8))
                sns.heatmap(self.df[numeric_cols].corr(), annot=True)
                plt.title("Correlation Heatmap")
                plt.savefig(output_path / "correlation_heatmap.png")
                plt.close()
    Python

    Step 4: Create Jupyter Notebook

    Create notebooks/analysis.ipynb:

    # Cell 1
    import sys
    sys.path.append('../src')
    
    from data_analysis.analyzer import DataAnalyzer
    import pandas as pd
    
    # Cell 2
    # Create sample data
    data = pd.DataFrame({
        'x': range(100),
        'y': [i**2 + 10*i for i in range(100)],
        'category': ['A' if i % 2 == 0 else 'B' for i in range(100)]
    })
    data.to_csv('sample_data.csv', index=False)
    
    # Cell 3
    analyzer = DataAnalyzer('sample_data.csv')
    df = analyzer.load_data()
    stats = analyzer.basic_stats()
    print(stats)
    
    # Cell 4
    analyzer.create_plots()
    Python

    Step 5: Run Jupyter

    uv run jupyter notebook notebooks/
    Bash

    Lab 3: Web API with FastAPI

    Objective: Build a REST API using FastAPI and uv

    Time: 60 minutes

    Step 1: Initialize API Project

    uv init todo-api
    cd todo-api
    Bash

    Step 2: Add Web Dependencies

    uv add fastapi uvicorn pydantic sqlalchemy python-multipart
    uv add --dev pytest httpx pytest-asyncio
    Bash

    Step 3: Create API Structure

    Create src/todo_api/main.py:

    from fastapi import FastAPI, HTTPException
    from pydantic import BaseModel
    from typing import List, Optional
    import uuid
    from datetime import datetime
    
    app = FastAPI(title="Todo API", version="1.0.0")
    
    class TodoCreate(BaseModel):
        title: str
        description: Optional[str] = None
    
    class Todo(BaseModel):
        id: str
        title: str
        description: Optional[str] = None
        completed: bool = False
        created_at: datetime
    
    # In-memory storage (use database in production)
    todos: List[Todo] = []
    
    @app.get("/")
    async def root():
        return {"message": "Todo API is running!"}
    
    @app.post("/todos/", response_model=Todo)
    async def create_todo(todo: TodoCreate):
        new_todo = Todo(
            id=str(uuid.uuid4()),
            title=todo.title,
            description=todo.description,
            created_at=datetime.now()
        )
        todos.append(new_todo)
        return new_todo
    
    @app.get("/todos/", response_model=List[Todo])
    async def get_todos():
        return todos
    
    @app.get("/todos/{todo_id}", response_model=Todo)
    async def get_todo(todo_id: str):
        for todo in todos:
            if todo.id == todo_id:
                return todo
        raise HTTPException(status_code=404, detail="Todo not found")
    
    @app.put("/todos/{todo_id}", response_model=Todo)
    async def update_todo(todo_id: str, completed: bool):
        for todo in todos:
            if todo.id == todo_id:
                todo.completed = completed
                return todo
        raise HTTPException(status_code=404, detail="Todo not found")
    
    @app.delete("/todos/{todo_id}")
    async def delete_todo(todo_id: str):
        global todos
        todos = [todo for todo in todos if todo.id != todo_id]
        return {"message": "Todo deleted"}
    Python

    Step 4: Add Tests

    Create tests/test_api.py:

    import pytest
    from fastapi.testclient import TestClient
    from src.todo_api.main import app
    
    client = TestClient(app)
    
    def test_root():
        response = client.get("/")
        assert response.status_code == 200
        assert response.json() == {"message": "Todo API is running!"}
    
    def test_create_todo():
        todo_data = {"title": "Test Todo", "description": "Test Description"}
        response = client.post("/todos/", json=todo_data)
        assert response.status_code == 200
        data = response.json()
        assert data["title"] == "Test Todo"
        assert data["completed"] == False
    
    def test_get_todos():
        response = client.get("/todos/")
        assert response.status_code == 200
        assert isinstance(response.json(), list)
    Python

    Step 5: Run the API

    # Run development server
    uv run uvicorn src.todo_api.main:app --reload
    
    # Run tests
    uv run pytest tests/
    Bash

    Lab 4: Workspace Management

    Objective: Create a multi-package workspace

    Time: 30 minutes

    Step 1: Initialize Workspace

    mkdir my-workspace
    cd my-workspace
    Bash

    Step 2: Create Workspace Configuration

    Create pyproject.toml:

    [tool.uv.workspace]
    members = [
        "packages/*",
        "services/*",
    ]
    
    [tool.uv.workspace.dependencies]
    pytest = ">=7.0.0"
    black = ">=22.0.0"
    INI

    Step 3: Create Shared Package

    mkdir -p packages/shared-utils
    cd packages/shared-utils
    uv init --lib
    Bash

    Edit packages/shared-utils/pyproject.toml:

    [project]
    name = "shared-utils"
    version = "0.1.0"
    description = "Shared utilities"
    dependencies = ["requests>=2.28.0"]
    INI

    Create packages/shared-utils/src/shared_utils/http.py:

    import requests
    from typing import Dict, Any
    
    def make_request(url: str, method: str = "GET", **kwargs) -> Dict[Any, Any]:
        """Make HTTP request with error handling."""
        response = requests.request(method, url, **kwargs)
        response.raise_for_status()
        return response.json()
    Python

    Step 4: Create Service Using Shared Package

    cd ../..
    mkdir -p services/web-service
    cd services/web-service
    uv init
    Bash

    Edit services/web-service/pyproject.toml:

    [project]
    name = "web-service"
    version = "0.1.0"
    dependencies = [
        "shared-utils",
        "fastapi>=0.100.0",
        "uvicorn>=0.23.0",
    ]
    INI

    Step 5: Sync Workspace

    cd ../..
    uv sync
    Bash

    21. Resources & Community

    Official Resources

    Community

    Learning Resources

    Contributing

    • Contributing Guide: CONTRIBUTING.md
    • Development Setup: Follow the repository README
    • Feature Requests: Open GitHub issues with feature requests
    • Ruff: Fast Python linter (same team)
    • Astral Ecosystem: Other Python tooling by Astral

    Conclusion

    This comprehensive guide has taken you on a complete journey through Python uv, from understanding its revolutionary architecture to mastering advanced optimization techniques. You now have the knowledge and practical skills to leverage uv’s full potential in your Python development workflow.

    🎯 Key Takeaways

    ConceptTraditional Approachuv Advantage
    Speedpip: 45s for 50 packagesuv: 3s for 50 packages (15x faster)
    WorkflowMultiple tools (pip, venv, pip-tools)Single unified tool
    ResolutionBasic dependency handlingAdvanced conflict resolution
    EnvironmentsManual virtual env managementAutomatic environment handling
    Python VersionsExternal tools (pyenv)Built-in Python management
    Reproducibilityrequirements.txt limitationsComprehensive lock files

    πŸš€ Your uv Journey Map

    graph TD
        A[Beginner] --> B[Install uv]
        B --> C[Create first project]
        C --> D[Master basic commands]
    
        D --> E[Intermediate]
        E --> F[Environment management]
        F --> G[Python version control]
        G --> H[Project configuration]
    
        H --> I[Advanced]
        I --> J[Workspaces & monorepos]
        J --> K[Performance optimization]
        K --> L[CI/CD integration]
    
        L --> M[Expert]
        M --> N[Custom tooling]
        N --> O[Team leadership]
        O --> P[Community contribution]
    
        style A fill:#ffeb3b
        style E fill:#ff9800
        style I fill:#2196f3
        style M fill:#4caf50

    πŸ“ˆ ROI of Adopting uv

    Individual Developer Benefits:

    • ⏱️ Time Savings: 80% reduction in dependency installation time
    • 🧠 Cognitive Load: Single tool instead of multiple tools
    • πŸ”’ Reliability: Fewer dependency conflicts and issues
    • πŸ“± Modern UX: Intuitive commands and helpful output

    Team Benefits:

    • πŸ”„ Consistency: Identical environments across all developers
    • πŸš€ CI/CD Speed: Faster build and deployment pipelines
    • πŸ“¦ Simplified Onboarding: New developers productive faster
    • πŸ›‘οΈ Security: Built-in vulnerability scanning and verification

    Organizational Benefits:

    • πŸ’° Cost Reduction: Less time spent on environment issues
    • πŸ“Š Productivity: Faster iteration cycles
    • πŸ”§ Maintenance: Reduced DevOps overhead
    • 🌟 Innovation: More time for feature development

    Immediate Actions (This Week)

    1. Install uv on your development machine
    2. Create a test project to familiarize yourself with commands
    3. Migrate one small project to uv
    4. Share findings with your team

    Short-term Goals (This Month)

    1. Standardize on uv for new projects
    2. Update CI/CD pipelines to use uv
    3. Create team documentation and best practices
    4. Train team members on uv usage

    Long-term Vision (This Quarter)

    1. Migrate all active projects to uv
    2. Optimize workspace configurations for monorepos
    3. Implement advanced features like custom tools
    4. Contribute back to the uv community

    πŸ† Success Metrics

    Track your uv adoption success with these metrics:

    • Installation Time: Measure before/after dependency installation
    • CI/CD Duration: Compare build pipeline execution times
    • Environment Issues: Count dependency-related problems per month
    • Developer Satisfaction: Survey team happiness with tooling
    • Onboarding Time: Time for new developers to become productive

    🌟 The Future of Python Development

    uv represents more than just a tool upgradeβ€”it’s a paradigm shift toward:

    • Unified Development Experience: Single tool for all Python needs
    • Performance-First Design: Speed as a core feature, not an afterthought
    • Developer Happiness: Intuitive interfaces and helpful feedback
    • Ecosystem Integration: Standards-compliant and interoperable
    • Continuous Innovation: Rapid feature development and community feedback

    🀝 Join the Community

    The uv community is vibrant and welcoming. Consider:

    1. Sharing your migration story on social media
    2. Contributing to documentation improvements
    3. Reporting bugs and feature requests on GitHub
    4. Helping other developers in Discord and forums
    5. Creating tutorials and examples for specific use cases

    πŸ’‘ Final Recommendations

    For Beginners

    • Start with simple projects to build confidence
    • Focus on core commands before exploring advanced features
    • Don’t be afraid to ask questions in the community
    • Practice with the hands-on labs in this guide

    For Experienced Developers

    • Leverage uv’s advanced features for complex projects
    • Share your expertise with team members
    • Contribute to improving uv’s ecosystem
    • Explore integration opportunities with your existing toolchain

    For Teams and Organizations

    • Plan migration strategy carefully with pilot projects
    • Invest in team training and documentation
    • Establish uv best practices and standards
    • Monitor adoption metrics and gather feedback

    πŸŽ‰ Closing Thoughts

    Python development has never been more exciting. With uv, we have a tool that not only solves today’s package management challenges but anticipates tomorrow’s needs. By mastering uv, you’re not just improving your current workflowβ€”you’re investing in the future of Python development.

    The journey from traditional Python tooling to uv represents a fundamental shift in how we think about dependency management, environment isolation, and developer productivity. As you continue your uv journey, remember that every expert was once a beginner, and every small optimization compounds into significant productivity gains.

    Whether you’re building the next breakthrough in AI, crafting elegant web applications, or analyzing complex datasets, uv provides the foundation for a faster, more reliable, and more enjoyable Python development experience.

    Welcome to the future of Python development. Welcome to uv! πŸš€


    πŸ“š Additional Resources

    Continue Learning:

    Share Your Success:

    • Tweet about your uv experience with #uvpython
    • Write blog posts about your migration journey
    • Speak at local Python meetups about uv
    • Create tutorials for your specific use cases

    This guide is a living document, updated regularly by the Python community. For the latest version, visit the official uv documentation. Happy coding!


    Discover more from Altgr Blog

    Subscribe to get the latest posts sent to your email.

    Leave a Reply

    Your email address will not be published. Required fields are marked *