Home > Blockchain >  Set `__version__` of module from a file when configuring setuptools using `setup.cfg` without `setup
Set `__version__` of module from a file when configuring setuptools using `setup.cfg` without `setup

Time:05-25

I’m following PyPA’s current guidance to use only setup.cfg without setup.py for configuring metadata when building a package for distribution. (“Static metadata (setup.cfg) should be preferred. Dynamic metadata (setup.py) should be used only as an escape hatch when absolutely necessary. setup.py used to be required, but can be omitted with newer versions of setuptools and pip.”)

To be concrete, I’m working with the following directory/file structure:

my-project/
├── LICENSE
├── pyproject.toml
├── README.md
├── setup.cfg
├── src/
│   └── my_package/
│       ├── __init__.py
│       └── my_module.py
└── tests/

(If you’re unfamiliar with this structure that has a src/ directory intermediating between the project directory and the import-package directory, it’s the structure given in the Packaging Python Projects tutorial and argued for by Ionel Cristian Mărieș and Mark Smith, et al. See also § “Using a src/ layout” in Configuring setuptools using setup.cfg files.)

I had been successfully specifying the version number in setup.cfg simply with:

[metadata]
version = "0.0.1"

However, PyPA et al. have discussed the concept of “single-sourcing the package version,” which basically means AFAICT moving the definition of the version outside of setup.py and setup.cfg to (a) make it more broadly accessible by other tools and (b) put the definition of the version into a file that’s within the import-package directory (viz., my-project/src/my_package) and therefore installed with the code. (Admittedly, my use case is so simple there may be little benefit to moving the definition outside setup.cfg, but I’m drawn to exploring best practices—perhaps irrationally so.

  • Related