Single-sourcing the Project Version#

Status da página:

Complete

Última revisão:

2024-10-07

Many Python distribution packages publish a single Python import package where it is desired that the runtime __version__ attribute on the import package report the same version specifier as importlib.metadata.version() reports for the distribution package (as described in Accessing version information at runtime).

It is also frequently desired that this version information be derived from a version control system tag (such as v1.2.3) rather than being manually updated in the source code.

Some projects may choose to simply live with the data entry duplication, and rely on automated testing to ensure the different values do not diverge.

Alternatively, a project’s chosen build system may offer a way to define a single source of truth for the version number.

In general, the options are:

  1. If the code is in a version control system (VCS), such as Git, then the version can be extracted from the VCS.

  2. The version can be hard-coded into the pyproject.toml file – and the build system can copy it into other locations it may be required.

  3. The version string can be hard-coded into the source code – either in a special purpose file, such as _version.txt (which must then be shipped as part of the project’s source distribution package), or as an attribute in a particular module, such as __init__.py. The build system can then extract it from the runtime location at build time.

Consult your build system’s documentation for their recommended method.

When the intention is that a distribution package and its associated import package share the same version, it is recommended that the project include an automated test case that ensures import_name.__version__ and importlib.metadata.version("dist-name") report the same value (note: for many projects, import_name and dist-name will be the same name).

Build System Version Handling#

The following are links to some build system’s documentation for handling version strings.