简体   繁体   中英

Python 3.5 vs Python 2.7: Modules importing submodules

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.

使用显式相对导入:

from . import subapi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM