简体   繁体   中英

Nested `ImportError` on Py3 but not on Py2

I'm having trouble understanding how nested imports work in a python project. For example:

test.py
package/
    __init__.py
    package.py
    subpackage/
        __init__.py

test.py :

import package

package/__init__.py :

from .package import functionA

package/package.py :

import subpackage

def functionA():
    pass

In Python 3.5 when I run test.py I get the following error, but no error in Python 2.7:

C:\Users\Patrick\Anaconda3\python.exe C:/Users/Patrick/Desktop/importtest/test.py
Traceback (most recent call last):
  File "C:/Users/Patrick/Desktop/importtest/test.py", line 1, in <module>
    import package
  File "C:\Users\Patrick\Desktop\importtest\package\__init__.py", line 1, in <module>
    from .package import functionA
  File "C:\Users\Patrick\Desktop\importtest\package\package.py", line 1, in <module>
    import subpackage
ImportError: No module named 'subpackage'

However if I run package.py with Python 3.5. I get no error at all.

This seems strange to me as when package.py is run on its own the line import subpackage works, but with it is being 'run' (don't know if this is the right terminology here) through the nested import, the same line cannot find subpackage .

Why are there differences between Python 2.7 and 3.5 in this case and how can this be resolved in a way that works for both 2.7.x and 3.x?

I think this might be due to the fact that import subpackage in the nested import counts as an implicit relative import in the nested import but not when package.py is run directly, but if I do import .subpackage instead, I get this error on both 2.7 and 3.5:

C:\Users\Patrick\Anaconda3\python.exe C:/Users/Patrick/Desktop/importtest/test.py
Traceback (most recent call last):
  File "C:/Users/Patrick/Desktop/importtest/test.py", line 1, in <module>
    import package
  File "C:\Users\Patrick\Desktop\importtest\package\__init__.py", line 1, in <module>
    from .package import functionA
  File "C:\Users\Patrick\Desktop\importtest\package\package.py", line 1
    import .subpackage
           ^
SyntaxError: invalid syntax

You should use:

from . import subpackage

in package/package.py .

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