problems importing sub packages in python: how should I write the __init__.py files

Viewed 113

I am new to building packages so bear with me. I am having a problem importing the subpackages of my latest python project.

My directory structure is the following:

├── package
│   ├── __init__.py
│   ├── subpackage_a
│   │   ├── __init__.py
│   │   └── functions_a.py
│   └── subpackage_b
│       ├── __init__.py
│       └── functions_b.py
└── setup.py

The files look as follows

setup.py :

from setuptools import setup
setup(name='test_package',
      version='0.3',
      description='',
      author='me',
      packages=['package']
      )

package/__init__.py: empty.

subpackage_a/__init__.py: from .functions_a import *

subpackage_b/__init__.py: from .functions_b import *

functions_a.py

contains

def hello_world_a():

    print('hello its a')

and functions_b.py contains

def hello_world_b():

    print('hello its b')

Now I open a virtualenv go to the setup.py's directory and I pip install .. I was expecting to access the functions contained in the subpackages a and b. But when I try to import the functions I get a module not found error.

from package.subpackage_a import hello_world_a 

ModuleNotFoundError: No module named 'package.subpackage_a'

and the same thing holds for subpackage_b. But if I import package this is recognised. I have a feeling that this approach used to work, as I have some old packages written this way which don't work any longer.

Perhaps I have to change my init.py files ? What am I doing wrong ?

1 Answers

setuptools.setup doesn't know that subpackage_a and subpackage_b exist. You only specified the top-level package. So it won't include these subpackages in the installation. Instead you should also specify them:

setup(
    ...,
    packages=['package', 'subpackage_a', 'subpackage_b']
)

This process can be automatized via find_packages():

from setuptools import find_packages

setup(
    ...,
    packages=find_packages()
)
Related