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

Implementing Dynamic Versioning Strategies

Set up your project to retrieve version numbers dynamically from version control or specific files during the build process.

In this lesson, you will learn how to automate your project's versioning so your package metadata stays in sync with your version control system or specialized configuration files without manual edits.

The Problem with Static Versioning

Until now, you’ve likely managed your version number by hardcoding it inside your pyproject.toml file (e.g., version = "0.1.0"). While simple, this creates a "syncing" burden: every time you tag a new release in Git, you must remember to update your configuration file. If you forget, your distribution metadata won't match your source code history, leading to confusion during deployment.

Implementing Dynamic Versioning

To automate this, we use a build backend that supports dynamic versioning. Instead of declaring a static string, we delegate version resolution to a plugin (like setuptools-scm or hatch-vcs). These tools inspect your Git history to calculate the version based on your latest tag.

For example, using hatchling as your build backend, you can configure your pyproject.toml to extract the version dynamically:

[build-system]
requires = ["hatchling", "hatch-vcs"]
build-backend = "hatchling.build"

[project]
name = "my-awesome-package"
dynamic = ["version"]

[tool.hatch.version]
source = "vcs"

How It Works

  1. The Build Process: When you run a build command (like uv build), the backend looks for the dynamic = ["version"] field.
  2. VCS Lookup: The plugin (e.g., hatch-vcs) runs a command similar to git describe behind the scenes.
  3. Metadata Injection: It injects the resulting version string into the final package metadata, ensuring your distribution always reflects the actual state of your repository.

This approach is powerful because it treats your Git tags as the "source of truth." You simply create a tag—git tag v1.2.0—and the next time you build your package, the version is automatically detected and correctly incremented, eliminating human error from the release process.

Key Takeaway: Dynamic versioning allows your project to derive its version metadata directly from your version control system, ensuring consistency between your Git history and your released distribution packages.