Getting Package Version at Runtime
Automatically setting your project’s version is all well and good, but you
usually also want to expose that version at runtime, usually via a
__version__ variable. There are three options for doing this:
Use the
version()function fromimportlib.metadatato get your package’s version, like so:from importlib.metadata import version __version__ = version("mypackage")
Note that
importlib.metadatawas only added to Python in version 3.8. If you wish to support older Python versions, use the importlib-metadata backport available on PyPI for those versions, e.g.:import sys if sys.version_info >= (3, 8): from importlib.metadata import version else: from importlib_metadata import version __version__ = version("mypackage")
If relying on the backport, don’t forget to include
importlib-metadata; python_version < "3.8"in your project’sinstall_requires!Fill out the
[tool.versioningit.write]subtable inpyproject.tomlso that the project version will be written to a file in your Python package which you can then import or read. For example, if your package is namedmypackageand is stored in asrc/directory, you can write the version to a Python filesrc/mypackage/_version.pylike so:[tool.versioningit.write] file = "src/mypackage/_version.py"
Then, within
mypackage/__init__.py, you can import the version like so:from ._version import __version__
Alternatively, you can write the version to a text file, say,
src/mypackage/VERSION:[tool.versioningit.write] file = "src/mypackage/VERSION"
and then read the version in at runtime with:
from pathlib import Path __version__ = Path(__file__).with_name("VERSION").read_text().strip()
(New in version 1.1.0) Use the onbuild step and its custom hooks to create sdists & wheels in which some file has been modified to contain the line
__version__ = "<project version>"or similar while leaving your repository’s contents alone.
Tip
Wondering which of write and onbuild is right for your project?
See this table for a comparison:
|
|
|
|---|---|---|
Should affected file be under version control? |
No |
Yes |
Affected file must already exist? |
No |
Yes |
Modifies working tree? [1] |
Yes |
No |
Run when installing in editable mode? |
Yes |
No |