'version = attr: in setup.cfg, ModuleNotFoundError

In my Python project with the directory layout

.
├── justfile
├── pyproject.toml
├── README.md
├── setup.cfg
└── src
    └── foobar
        ├── __about__.py
        ├── __init__.py
        └── main.py

__about__.py reads

__version__ = "1.0.0"

I would like to use this version info in setup.cfg. I tried

[metadata]
name = foobar
version = attr: foobar.__about__.__version__

[options]
package_dir =
    =src
packages = find:
install_requires =
    rich
python_requires = >=3.6

[options.packages.find]
where=src

but this still tries to import foobar, resulting in ModuleNotFoundErrors from foobars dependencies when trying to evaluate the version string.

The __init__.py reads

from .main import solve
from .__about__ import __version__

I had been under the impression that after this PR has been merged, just the AST of the attr was evaluated. (See also this question.)

Any idea what might be wrong?



Solution 1:[1]

I found the issue. In __init__.py, the __version__ must be imported before all external dependencies. This

from .__about__ import __version__
from .main import solve

works.

Solution 2:[2]

src is not part of the package import path (you wouldn't do import src.foobar with your installed package), it's just a directory.

Try

version = attr:foobar.__about__.__version__

instead (assuming you've set up the src/ layout in setup.cfg).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nico Schlömer
Solution 2 AKX