Skip to content Skip to sidebar Skip to footer

Import Error Despite __init__.py Exists In The Folder That Contains The Target Module

I have the following directory structure inside a virtualenv: /dir_a/dir_b/__init__.py /dir_a/dir_b/module_1.py /dir_a/dir_b/module_2.py /dir_a/dir_c/__init__.py /dir_a/dir_c/modul

Solution 1:

I would not mess with PYTHONPATH in this case. I think what you need is called Intra-package References. In your specific case, to import module_4 from a submodule like module_3 you need:

from .. import module_4

I will try to recreate a contrived example just to try to explain myself:

module_1.py:

# import sibling submoduleprint'module_1'from . import module_2

module_2.py:

print'module_2'

module_3.py:

# import parent moduleprint'module_3'from .. import module_4

module_4.py:

# import child submodule
print'module_4'import dir_b.module_1

And an extra bonus special module that will transitively import all the others. Create a module_5.py inside package dir_a next to module_4.

module_5.py:

print'module_5'import dir_c.module_3

Now, from the dir_a parent folder you can see what happens when run a different modules/submodules:

$ python -m dir_a.module_4
module_4
module_1
module_2

$ python -m dir_a.dir_c.module_3
module_3
module_4
module_1

$ python -m dir_a.module_5
module_5
module_3
module_4
module_1
module_2

Post a Comment for "Import Error Despite __init__.py Exists In The Folder That Contains The Target Module"