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
- The Build Process: When you run a build command (like
uv build), the backend looks for thedynamic = ["version"]field. - VCS Lookup: The plugin (e.g.,
hatch-vcs) runs a command similar togit describebehind the scenes. - 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.