Python 3.5 vs Python 2.7: Modules importing submodules

限于喜欢 提交于 2020-01-11 05:09:05

问题


I have been googling this for the past hours and can't find an equivalent question anywhere. Also the documentation for 2.7 and 3.5 seem identical, so I don't think this behavior is documented.

Here is my directory structure:

project
    -- project.py
    -- api
        -- __init__.py
        -- subapi
            -- __init__.py

contents of project/project.py: import api

contents of project/api/__init__.py: import subapi

If I execute python project.py (using python 2.7) from inside the projects folder, it returns without an error. If I do the same with python 3 (python3 project.py), then it crashes with

Traceback (most recent call last):
  File "project.py", line 1, in <module>
    import api
  File "/home/me/Documents/project/api/__init__.py", line 1, in <module>
    import subapi
ImportError: No module named 'subapi'

If I rewrite the import statement to use paths relative to the projects directory (import api.subapi), then it works with python 2 as well as 3. It's not a satisfying solution though because that requires me to reference parent modules from within sub modules which kind of defeats the idea of modularity..

Does anyone have an idea what I can do to get the behavior of python2 back? The module search algorithm should prioritize searching in the local directory of the file using the import statement. It should also prioritize these files above built in modules by the way. Try importing a module 'test'..

--EDIT-- I was asked by stackoverflow to differentiate my question from another called "How to do relative imports". I think this question is different because I am asking specifically about differences between two versions. Using relative imports is the solution, not the question.


回答1:


Use an explicit relative import:

from . import subapi


来源:https://stackoverflow.com/questions/42008881/python-3-5-vs-python-2-7-modules-importing-submodules

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