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

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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alwin07