pyproject.toml

pyproject.toml - dynamic versioning from file


With pyproject.toml is it possible to set the version from a file in the module at runtime?

Ex ranchercli/ranchercli.py (comes from a git commit hook doing dynamic versioning):

__VERSION__ = open("VERSION.TXT", "r").read().strip()

works fine in the module:

>>> import ranchercli.ranchercli
>>> ranchercli.ranchercli.__VERSION__ 
'0.14.1'

In pyproject.toml:

[project]
name = "ranchercli"
dynamic = ["version"]
:
[tool.setuptools.dynamic]
version = {attr = "ranchercli.ranchercli.__VERSION__"}

But when I try pip install -e . or any other pip:

File "C:\Users\mobj\AppData\Local\Temp\pip-build-env-8129o6il\overlay\Lib\site-packages\setuptools\config\expand.py", line 75, in __getattr__
  raise AttributeError(f"{self.name} has no attribute {attr}") from e
      AttributeError: ranchercli.ranchercli has no attribute __VERSION__

Solution

  • Dynamic versioning works differently on different build backends. Judging by [tool.setuptools.dynamic], you're using setuptools.

    For setuptools, there is an easier way to get the version from a file:

    [tool.setuptools.dynamic]
    version = {file = "VERSION.TXT"}
    

    Nevertheless, if you really want to get the version from a module attribute, check your project structure. Provide the directory tree, the Python version and the full pyproject.toml, so we can reproduce the error and debug what is wrong.