Monday, 24 July 2023

How to properly capture library / package version in my package when using pyproject.toml to build

I have moved away from a setup.py file to build my packages / libraries to fully using pyproject.toml. I prefer it overall, but it seems that the version placed in the pyproject.toml does not propagate through the build in any way. So I cannot figure out how to inject the package version -- or any other metadata provided in the pyproject.toml -- into my package.

A google search led me to this thread, which had some suggestions. They all seemed like hacks, but I tried this one because it seemed best:

from pip._vendor import tomli ## I need to be backwards compatible to Python 3.8

with open("pyproject.toml", "rb") as proj_file:
    _METADATA = tomli.load(proj_file)

DESCRIPTION = _METADATA["project"]["description"]
NAME = _METADATA["project"]["name"]
VERSION = _METADATA["project"]["version"]

It worked fine upon testing, but I did not test robustly enough: once I tried to install this in a fresh location / machine, it failed because the pyproject.toml file is not part of the package installation. (I should have realized this.)


So, what is the right / best way to provide metadata, like the package version, to my built package? I need the following requirements:

  1. I only want to provide the information once, in the pyproject.toml. (I know that if I need to repeat a value, at some point there will be a mismatch.)
  2. I want the information to be available to the end user, so that someone who installs the package can do something like mypackage.VERSION from her interactive Python session.
  3. I want to only use pyproject.toml and Poetry / PDM. (I actually use PDM, but I know that Poetry is more popular. The point is that I don't want a setup.py or setup.cfg hack. I want to purely use the new way.)


from How to properly capture library / package version in my package when using pyproject.toml to build

No comments:

Post a Comment