Import error despite __init__.py exists in the folder that contains the target module

天大地大妈咪最大 提交于 2021-01-29 18:05:28

问题


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/module_3.py
/dir_a/__init__.py
/dir_a/module_4.py

Inside module_4.py, I can successfully import module_1.py, module_2.py and module_3.py. On the other hand, I cannot import module_4.py within module_3.py (e.g. import dir_a.module_4). It complains: "No module named dir_a.module_4"

What am I missing here? Do I need to mess with PYTHONPATH of my virtualenv here? If so, why is the import of module_1.py, module_2.py and module_3.py all fine without touching PYTHONPATH?


回答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 submodule
print 'module_1'
from . import module_2

module_2.py:

print 'module_2'

module_3.py:

# import parent module
print '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


来源:https://stackoverflow.com/questions/26369499/import-error-despite-init-py-exists-in-the-folder-that-contains-the-target-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!