简体   繁体   English

在Py3而不是Py2上嵌套了“ ImportError”

[英]Nested `ImportError` on Py3 but not on Py2

I'm having trouble understanding how nested imports work in a python project. 我在理解嵌套导入如何在python项目中工作时遇到了麻烦。 For example: 例如:

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

test.py : test.py

import package

package/__init__.py : package/__init__.py

from .package import functionA

package/package.py : 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: 在Python 3.5中运行test.py时,出现以下错误,但在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. 但是,如果我使用Python 3.5运行package.py 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 . 这对我来说很奇怪,因为当package.py运行时,行import subpackage可以工作,但是通过嵌套导入(同一行)正在“运行”(不知道这里是否是正确的术语)找不到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? 为什么在这种情况下Python 2.7和3.5之间存在差异,并且如何以适用于2.7.x和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: 我认为这可能是由于嵌套导入中的import subpackage被视为嵌套导入中的隐式相对导入,而不是直接运行package.pyimport .subpackage ,但是如果我改为import .subpackageimport .subpackage收到此错误2.7和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 . package/package.py

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

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