Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 525
Philon Avatar asked Feb 02 '17 17:02

Philon


1 Answers

Use an explicit relative import:

from . import subapi
like image 82
user2357112 supports Monica Avatar answered Sep 28 '22 00:09

user2357112 supports Monica