Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Single sourcing a python package version using importlib.metadata.version()
try:
# importlib.metadata is present in Python 3.8 and later
import importlib.metadata as importlib_metadata
except ImportError:
# use the shim package importlib-metadata pre-3.8
import importlib_metadata as importlib_metadata
try:
__version__ = importlib_metadata.version(__package__ or __name__)
except importlib_metadata.PackageNotFoundError:
__version__ = "0.0.0"
# If you're using a pyproject.toml, pick the appropriate format below
### poetry ###
[tool.poetry]
name = "my_package"
version = "1.2.3"
# add this in addition to whatever else you've got in here
[tool.poetry.dependencies]
importlib-metadata = { version = "~=1.0", python = "<3.8" }
### setuptools ###
[metadata]
name = "my_package"
version = "1.2.3"
# add this in addition to whatever else you've got in here
[options]
install_requires = "importlib-metadata ~= 1.0 ; python_version < '3.8'"
### PEP621 ###
[project]
name = "my_package"
version = "1.2.3"
# add this in addition to whatever else you've got in here
dependencies = [
"importlib-metadata ~= 1.0 ; python_version < '3.8'"
]
# If you're using setup.py, you either add the following string to the install_requires list
# "importlib-metadata ~= 1.0 ; python_version < '3.8'"
# or include that string under options.install_requires in setup.cfg

You can single-source your package version, setting the package version only in the project data in pyproject.toml or setup.py, using importlib.metadata

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment