'Trying to read __version__ with setuptools (setup.py) results in FileNotFoundError during build

EDIT: See answer below for explanation of my mistake, and the solution.

I was trying to follow the instructions in @dnozay's answer on how to read __version__ in setup.py from a file.

My (simplified) project file tree is:

setup.py    
my_module
├── __init.py__
├── _version.py
└── myclasses.py

As the answer instructs, I expose __version__ in _version.py:

# _version.py

_version = {
    'major': 1,
    'minor': 0,
    'revis': 0,
}
__version__ = '.'.join([str(a) for a in _version.values()])

and my setup.py contains:

from setuptools import setup, find_packages
from distutils.util import convert_path

main_ns = {}
ver_path = convert_path("my_module/_version.py")
with open(ver_path) as ver_file:
    exec(ver_file.read(), main_ns)

setup(...
    version=main_ns['__version__'],
    package_dir={"": "my_module"},
    packages=find_packages(where="my_module"),
    ...)

However, when I try to build the package with python3 -m build I get a FileNotFoundError

* Building wheel from sdist
* Creating virtualenv isolated environment...
* Installing packages in isolated environment... (setuptools>=45)
* Getting dependencies for wheel...
Traceback (most recent call last):
  File "/home/username/.local/lib/python3.8/site-packages/pep517/in_process/_in_process.py", line 363, in <module>
    main()
  File "/home/username/.local/lib/python3.8/site-packages/pep517/in_process/_in_process.py", line 345, in main
    json_out['return_val'] = hook(**hook_input['kwargs'])
  File "/home/username/.local/lib/python3.8/site-packages/pep517/in_process/_in_process.py", line 130, in get_requires_for_build_wheel
    return hook(config_settings)
  File "/tmp/build-env-xlvmof6k/lib/python3.8/site-packages/setuptools/build_meta.py", line 177, in get_requires_for_build_wheel
    return self._get_build_requires(
  File "/tmp/build-env-xlvmof6k/lib/python3.8/site-packages/setuptools/build_meta.py", line 159, in _get_build_requires
    self.run_setup()
  File "/tmp/build-env-xlvmof6k/lib/python3.8/site-packages/setuptools/build_meta.py", line 174, in run_setup
    exec(compile(code, __file__, 'exec'), locals())
  File "setup.py", line 10, in <module>
    with open(ver_path) as ver_file:
FileNotFoundError: [Errno 2] No such file or directory: 'my_module/_version.py'


Solution 1:[1]

Alright, I see my mistake. The find_packages() function was trying to find the module files in my_package/my_package/, that is why the build was failing, my_package/my_package/_version.py doesn't exist.

To fix it I changed setup() to:

setup=(...
    version=main_ns['__version__'],
    packages=find_packages(where='.')
    ...)

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 Rui ApĆ³stolo