How to add dynamic versioning to uv projects
Dynamic versioning generates version numbers from Git tags instead of requiring manual updates to a static version string in pyproject.toml. This guide sets it up using uv-dynamic-versioning.
Prerequisites
- A Git repository for your Python project
- uv installed on your system
Configure the build system
Update pyproject.toml to use uv-dynamic-versioning as a build dependency:
[build-system]
requires = ["hatchling", "uv-dynamic-versioning"]
build-backend = "hatchling.build"Set the version source
Add a version source and mark the version field as dynamic:
[project]
name = "your-project"
dynamic = ["version"] # Remove any static version = "..." line
[tool.hatch.version]
source = "uv-dynamic-versioning"Create a Git tag
Tag a commit following the default pattern (a v prefix followed by a semantic version):
$ git tag v0.1.0
Build and verify
$ uv build
The built distribution’s filename includes the version derived from the tag.
Add a fallback version
CI runners like Dependabot sometimes check out code without full Git history. A fallback prevents build failures in those environments:
[tool.uv-dynamic-versioning]
fallback-version = "0.0.0"Expose the version at runtime
To make the version accessible within the package:
# your_package/__init__.py
import importlib.metadata
try:
__version__ = importlib.metadata.version(__name__)
except importlib.metadata.PackageNotFoundError:
__version__ = "0.0.0" # Fallback for development modeThis reads the version from installed package metadata, so it stays in sync with the Git tag without duplicating the value.
Related
- uv-dynamic-versioning on GitHub
- pyproject.toml reference covers project metadata fields including
dynamic - What is a build backend? explains how hatchling and other backends work
- Why does uv use hatch as a backend? covers the default build backend for uv projects
- uv reference documents the
uv buildanduv publishcommands
Get Python tooling updates
Subscribe to the newsletter