🐍

Streamlining Python Projects with UV

Apr 15, 2025

Notes on UV Python Package Manager

Introduction

  • If you're still using pip or manually creating virtual environments, this video introduces a new tool called UV.
  • UV is a Python package and project manager almost 100 times faster than pip in certain situations.
  • It simplifies managing Python tools like virtual environments and installing dependencies.

Installing UV

  • Installation Methods:
    • For Mac/Linux: Use curl or wget, or run pip install uv.
    • For Windows: Use Powershell or pip install uv.
  • After installation, restart your terminal to start using UV.

Basic Usage of UV

  1. Verify Installation:

    • Run the command uv in your terminal to check if it works and shows available commands.
  2. Manage Python Versions:

    • List available Python versions: uv python list.
    • Install a specific version: uv python install <version> (e.g., uv python install 3.8).
    • Search for a specific version: uv python find <version>.
    • Uninstall a version: uv python uninstall <version>.
  3. Running Python Scripts:

    • Use uv run <script_name>.py to run a script.
    • Specify Python version: uv run --python <version> <script_name>.py.
    • Handle dependencies: Use uv run --with <dependency> to install and run scripts with specific packages.

Adding Dependencies to Scripts

  • You can add dependencies directly to your script via the command:
    • uv init-script <script_name.py> --python <version> to set up Python version and dependencies.
  • Add dependencies using:
    • uv add-d-script <script_name.py> <dependency>.

Managing Python Projects with UV

  1. Creating a New Project:

    • Navigate to the desired project directory and type uv init to set up project files and a git repository.
    • Files created include:
      • main.py (entry point)
      • pyproject.toml (detailed requirements file)
      • .gitignore
  2. Adding/Removing Dependencies:

    • Use uv add <dependency> to install and add to pyproject.toml.
    • Use uv remove <dependency> to uninstall the package and update the file.
  3. Virtual Environment Management:

    • UV creates and manages a virtual environment automatically, syncing it with the project's dependencies.
  4. Lock Files:

    • uv.lock file helps maintain exact versions of packages used in the project, useful for source control.

Syncing Dependencies

  • Use uv sync to sync the virtual environment with the dependencies in pyproject.toml manually, or it runs automatically with uv run.

Final Notes

  • You can still use legacy pip commands by typing uv pip.
  • UV simplifies Python project management and drastically improves speed compared to traditional methods.

Conclusion

  • UV is designed to enhance your Python coding experience, allowing for faster project setup and dependency management.