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?
The pyproject. toml file was introduced in PEP-518 (2016) as a way of separating configuration of the build system from a specific, optional library (setuptools) and also enabling setuptools to install itself without already being installed.
To update to the latest versions, use the update command. This will fetch the latest matching versions (according to your pyproject. toml file) and update the lock file with the new versions. (This is equivalent to deleting the poetry.
Yes, pyproject. toml is the specified file format of PEP 518 which contains the build system requirements of Python projects. This solves the build-tool dependency chicken and egg problem, i.e. pip can read pyproject.
It seems no official documentation exists yet around pyproject.toml and the PEPs aren’t user docs. It appears Pypa and the Python docs both continue talking about using setup.py. I was wondering if there was a place I wasn’t aware of perhaps? Or maybe some help to document it if I can find the time, but then where to start?
Modern Python packages can contain a pyproject.toml file, first introduced in PEP 518 and later expanded in PEP 517, PEP 621 and PEP 660 . This file contains build system requirements and information, which are used by pip to build the package.
You are right, no, it is not read from pyproject.toml. From the python docs was the predecessor to PEP 566 that first defined the field in the file PKG-INFO. Metadata is read from here. However, @ErikBjare is right that the version number is built using
In this blogpost, I'll show you a minimal example of a pyproject file which uses flit in order to install it's dependencies. Already back in 2016, PEP 518 was created which aimed to fix the catch-22 of setup.py files (it depending on libraries which can only be defined in the setup.py file).
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__)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With