GuyWithCookies
GuyWithCookies

Reputation: 640

Python - package can not import subpackages when installed with setup.py

I developed a python package which I want to use in another project. The package structure looks like the following example:

- foo
  - setup.py
  - README.md
  - foo
    - __init__.py
    - main.py
    - bar.py
    - sub_pkg1
       - __init__.py
       - example.py
    - sub_pkg2
       - __init__.py
       - example2.py

The bar.py File contains the Bar-Class which relies on the files in sub_pkg1 and sub_pkg2 which are imported like

from sub_pkg1 import example.py

The __init__.py files just import each python file in it's directory. For example the __init__.py of sub_pkg1:

from example import ExampleClass

The main.py File just imports the Bar Class and executes some methods of it.

from bar import Bar
bar = Bar()
bar.foo()

The setup.pyfile looks like the following:

from setuptools import setup, find_packages

setup(
    name='Bar',
    version='0.0.7',
    author='me',
    packages=find_packages()
)

When I run the main.py file directly from the package it works like a charm. However when I install it in my other project with pip using the command: (I don't want to publish the package to PyPi yet and just want to include the development-version in my other project)

pip install -e /path/to/package

and try to import it - I am getting the error:

ModuleNotFoundError: No module named 'example'

Do I need to export the sub_packages somehow?

I use Python 3.6

Upvotes: 0

Views: 1758

Answers (1)

Oli
Oli

Reputation: 1

instead of from sub_pkg1 import example.py use from sub_pkg1 import ExampleClass

as in __init__.py of sub_pkg1 and sub_pkg2 you have already imported ExampleClass and you are now free to directly import ExampleClass from sub_pkg1 anywhere in your project.

Read more about __init__.py and modules here: https://docs.python.org/3/tutorial/modules.html

Upvotes: 1

Related Questions