Setting up a Python monorepo to build multiple packages using UV involves organizing your repository structure, configuring each package with pyproject.toml, and using UV's commands to manage dependencies and build distributions. UV is a fast, modern tool for Python package management, similar to Poetry or Pip, but optimized for speed and efficiency. It supports building wheels and SDists for packages defined in pyproject.toml.
Below, I'll walk you through the process step by step. This assumes you're starting from scratch or adapting an existing repo.
1. Understand the Monorepo Structure
A Python monorepo typically contains multiple packages in a single repository. Each package can be independent, with its own dependencies and build configuration. This allows you to manage shared code, dependencies, or tools while building and publishing packages separately.
Example structure:
code
my-monorepo/
├── packages/ # Directory for individual packages
│ ├── package1/ # First package
│ │ ├── src/ # Source code
│ │ │ └── __init__.py
│ │ ├── tests/ # Tests
│ │ └── pyproject.toml # Package configuration
│ ├── package2/ # Second package
│ │ ├── src/
│ │ │ └── __init__.py
│ │ ├── tests/
│ │ └── pyproject.toml
│ └── ... # More packages as needed
├── tools/ # Optional: Shared scripts or utilities
│ └── build_all.py # Script to build all packages
├── pyproject.toml # Optional: Root-level config for the monorepo
├── poetry.lock # If using Poetry for the monorepo (not required with UV)
└── README.md
Why this structure? Each package has its own pyproject.toml, allowing UV to treat them as independent projects. The root might have shared configurations if needed.
2. Install UV
First, ensure UV is installed. You can install it via pip:
code
pip install uv
UV is a command-line tool, so once installed, you can run commands like uv --help to verify.
3. Configure Each Package
For each package (e.g., packages/package1), create a pyproject.toml file. This file defines the package metadata, dependencies, and build system.
Here's a basic example for packages/package1/pyproject.toml:
toml
[build-system]
requires = ["setuptools", "wheel"] # Or "hatchling" if you prefer
build-backend = "setuptools.build_meta"
[tool.uv]
# UV-specific configurations can go here if needed, but it's optional
[project] # PEP 621 metadata
name = "my-monorepo-package1"
version = "0.1.0"
description = "First package in the monorepo"
authors = [{name = "Your Name", email = "your.email@example.com"}]
dependencies = [
"requests>=2.0", # Example dependency
]
requires-python = ">=3.8"
[tool.setuptools.packages]
find = {} # Auto-discover packages in src/
# Optional: Add scripts, entry points, etc.
Key points:
Use [build-system] to specify how to build the package (e.g., using setuptools or Hatch).
The [project] section follows PEP 621 for modern package metadata.
Add dependencies under [project.dependencies]. UV will handle resolving and installing them.
Repeat this for each package (e.g., packages/package2/pyproject.toml).
If your packages share dependencies, you can manage them at the root level or use a shared requirements.txt, but UV will resolve them per package.
4. Build the Packages with UV
UV provides a build command to create wheels (.whl) and source distributions (.tar.gz) for each package. You can run this command in the directory of each package.
Step-by-Step Building:
Navigate to the package directory and run the build command:
code
cd packages/package1
uv build
This will generate output like dist/my-monorepo-package1-0.1.0-py3-none-any.whl in the dist folder.
UV automatically handles dependencies based on your pyproject.toml.
Repeat for other packages:
code
cd ../package2
uv build
Automating for Multiple Packages:
Building manually for each package can be tedious in a monorepo. You can write a simple script to automate this. For example, create a Python script in tools/build_all.py:
python
import subprocess
import os
from pathlib import Path
PACKAGES_DIR = Path("packages")
def build_package(package_dir: Path):
try:
subprocess.run(["uv", "build"], cwd=package_dir, check=True)
print(f"Successfully built {package_dir}")
except subprocess.CalledProcessError as e:
print(f"Error building {package_dir}: {e}")
if __name__ == "__main__":
for package in PACKAGES_DIR.iterdir():
if package.is_dir() and (package / "pyproject.toml").exists():
build_package(package)
Run the script from the root:
code
python tools/build_all.py
This will iterate through the packages directory, build each package with UV, and handle errors.
5. Manage Dependencies and Environments
UV excels at dependency management, so integrate it into your workflow:
Lock dependencies: In each package directory, run:
code
uv lock # Generates a uv.lock file
This creates a lockfile for reproducible builds.
Install dependencies for development: To set up a virtual environment for a package:
code
cd packages/package1
uv sync # Installs dependencies from pyproject.toml and uv.lock
This creates a virtual environment in .venv (or you can specify one).
For the entire monorepo: If you want a shared environment, you could run UV commands from the root, but it's better to keep environments per package to avoid conflicts.
6. Best Practices and Tips
Versioning: Use semantic versioning in each pyproject.toml. Tools like bump2version can help automate this.
Testing: Add tests to each package and run them with UV. For example:
code
uv run pytest # Assumes pytest is a dev dependency
First, add dev dependencies in pyproject.toml under [tool.uv.dev-dependencies] or similar.
Publishing: Once built, you can publish wheels to PyPI using:
code
uv publish # In the package directory, after building
CI/CD Integration: In a monorepo, use GitHub Actions or similar to automate builds. For example, a workflow that runs your build script on changes.
Common Pitfalls:
Dependency Conflicts: If packages share dependencies, ensure versions are compatible. UV's lockfiles help here.
Build System Compatibility: UV works best with modern build backends like Hatch or Setuptools. If you're migrating from Poetry, check for differences.
Python Versions: Test with multiple Python versions using UV's --python flag (e.g., uv build --python 3.9).
Performance: UV is fast, but for large monorepos, optimize your script to build in parallel using tools like concurrent.futures.
This setup should get you started. If you encounter issues, refer to the UV documentation (check the official repo or run uv --help). If your monorepo has more complex needs (e.g., shared code across packages), consider tools like Poetry's workspaces or Hatch's environments for additional features. Let me know if you need help with a specific part!