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 inimportlib.metadata
to get your package’s version, like so:from importlib.metadata import version __version__ = version("mypackage")
Note that
importlib.metadata
was 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.:try: from importlib.metadata import version except ImportError: 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.toml
so 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 namedmypackage
and is stored in asrc/
directory, you can write the version to a Python filesrc/mypackage/_version.py
like 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) Fill out the
[tool.versioningit.onbuild]
subtable inpyproject.toml
and configure yoursetup.py
to useversioningit
’s custom setuptools commands. This will allow you to create sdists & wheels in which some file has been modified to contain the line__version__ = "<project version>"
or similar while leaving your repository alone. See “The [tool.versioningit.onbuild] Subtable” for more information.
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 |
Requires configuration in |
No |
Yes |
Run when installing in editable mode? |
Yes |
No |
- 1
That is, the
write
method causes a file to be present (though likely ignored) in your repository after running, while theonbuild
method only modifies a file inside sdists & wheels and leaves the original copy in your repository unchanged.