Course contentsShow
← Python
Lesson 508 of 1,0608. Professional Tooling and PackagingFree lesson

Synchronizing Environments with Lock Files

Learn how to use uv sync to automatically update your virtual environment to match the exact specifications defined in your project lock file.

In this lesson, you will learn how to use uv sync to ensure your local virtual environment perfectly mirrors the locked specifications defined in your project.

The Problem of Environment Drift

In previous lessons, we discussed the risks of global environment pollution and the challenges of managing dependencies. Even with a requirements.txt file or a lock file generated by tools like uv, your local virtual environment can become "stale." Perhaps a colleague updated a dependency version in the lock file, or you manually installed a package in your local environment that isn't reflected in your project’s official configuration. If your environment doesn't match your lock file, you risk "it works on my machine" bugs.

Achieving Determinism with uv sync

The uv sync command is designed to resolve this discrepancy. It acts as the bridge between your uv.lock file and your local environment. When you run uv sync, the tool performs three critical actions:

  1. Comparison: It inspects your current virtual environment's installed packages.
  2. Analysis: It compares those packages against the exact versions, hashes, and markers defined in your uv.lock file.
  3. Reconciliation: It automatically uninstalls extra packages, updates outdated ones, and installs missing ones to ensure your environment is an identical clone of what the lock file dictates.

Example Workflow

Imagine you have defined your dependencies in a pyproject.toml file. After running uv lock to generate the deterministic dependency tree, your workflow to keep your environment healthy is simple:

# Update the environment to match the lock file
uv sync

If you modify your dependencies in the pyproject.toml later, you don't need to manually run pip install or pip uninstall. Simply run:

# Update the lock file and sync the environment in one go
uv lock
uv sync

By making uv sync a standard part of your development loop—especially after pulling the latest code from version control—you ensure that your execution environment remains consistent with your team's specifications, preventing subtle integration errors before they happen.

Key Takeaway: Use uv sync to automatically reconcile your virtual environment with your project's lock file, ensuring a deterministic and reliable development setup.