Search code examples
setuptoolssetup.pypython-packaging

Accessing modules in subdirectory when building pip package


This is my project structure currently;

repository/
|---- setup.py
|---- package_name/
      |---- __init__.py
      |---- module_a.py
      |---- subdir/
            |---- __init__.py
            |---- module_b.py

I install this with pip install . and leave the repository folder. Now when I try to import this package I can access module_a as shown below;

from package_name.module_a import ma

However on running the code below I get ModuleNotFoundError: No module named 'package_name.subdir';

from package_name.subdir.module_b import mb

Can someone explain how I can expose the modules in the subdirectory so that they may be imported from the package? I plan on uploading the package to PyPI.

If it helps, this is the repository - link


Solution

  • As explained by @sinoroc, the packages in my setup.py file were incorrect. The packages parameter (here) should have listed all packages and sub-packages, however a less tedious method is to use find_packages as shown below, which does this for you automatically.

    from setuptools import setup, find_packages
    setup(
        ...,
        packages=find_packages(),
        ...,
    )
    

    You can read more here.