简体   繁体   English

Python 3.5 vs Python 2.7:模块导入子模块

[英]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. 在过去的几个小时中,我一直在使用Google搜索,在任何地方都找不到等效的问题。 Also the documentation for 2.7 and 3.5 seem identical, so I don't think this behavior is documented. 此外,2.7和3.5的文档似乎相同,因此我认为没有记录这种行为。

Here is my directory structure: 这是我的目录结构:

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

contents of project/project.py : import api project/project.py内容: import api

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

If I execute python project.py (using python 2.7) from inside the projects folder, it returns without an error. 如果我从projects文件夹中执行python project.py (使用python 2.7),它将返回而没有错误。 If I do the same with python 3 ( python3 project.py ), then it crashes with 如果我对python 3( python3 project.py )进行相同操作,则崩溃

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.. 如果我重写import语句以使用相对于项目目录的路径( import api.subapi ),则它适用于python 2和3。虽然这不是令人满意的解决方案,因为这要求我从子模块中引用父模块。哪种方式打败了模块化的想法。

Does anyone have an idea what I can do to get the behavior of python2 back? 有谁知道我该怎么做才能恢复python2的行为? The module search algorithm should prioritize searching in the local directory of the file using the import statement. 模块搜索算法应优先使用import语句在文件的本地目录中搜索。 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". -编辑-stackoverflow要求我将我的问题与另一个称为“如何进行相对进口”的问题区分开。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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