Search code examples
pythonversionsetuptoolspyproject.toml

Using environment variables in `pyproject.toml` for versioning


I am trying to migrate my package from setup.py to pyproject.toml and I am not sure how to do the dynamic versioning in the same way as before. Currently I can pass the development version using environment variables when the build is for development.

The setup.py file looks similar to this:

import os

from setuptools import setup

import my_package


if __name__ == "__main__":
    dev_version = os.environ.get("DEV_VERSION")
    version = dev_version if dev_version else f"{my_package.__version__}"
    
    setup(
        name="my_package",
        version=version,
        ...
    )

Is there a way to do similar thing when using pyproject.toml file?


Solution

  • Another alternative that might be worth considering for your use case, if you use Git, is to use setuptools_scm. It uses your git tags to perform dynamic versioning. Your pyproject.toml would look something like this:

    [build-system]
    requires = ["setuptools", "setuptools-scm"]
    build-backend = "setuptools.build_meta"
    
    [tool.setuptools_scm]
    "version_scheme" = "post-release"
    "local_scheme" = "no-local-version"
    "write_to" = "mypackage/version.py"
    
    [tool.setuptools.package-dir]
    mypackage = "mypackage"
    
    [project]
    name = "mypackage"
    ...
    dynamic = ["version"]