How to specify version in only one place when using pyproject.toml?

Viewed 4601

My package version is defined in two places:

  • __version__ = 1.2.3 in mypackage/__init__.py
  • version = "1.2.3" in pyproject.toml (I am using Poetry)

I have to update both whenever I bump the version which is annoying and not DRY. Is there a way to make Python read the version from the TOML, or to make the TOML read the version from Python?

2 Answers

After you have installed your project - either in editable mode by poetry install or from the wheel - you can access several metadata via importlib.metadata (importlib_metadata for python < 3.8).

So keep the version only in the pyproject.toml and use this in your python code:

import importlib.metadata

__version__ = importlib.metadata.version("mypackage")

This code worked for me:

import importlib.metadata

__version__ = importlib_metadata.version(__package__ or __name__)

However, this only works if the package is already installed using pip or poetry.

On newer version (dot instead of underscore):

__version__ = importlib.metadata.version(__package__ or __name__)
Related