这里似乎已经有了一些关于python 3中相对导入的问题,但在浏览了许多之后,我仍然没有找到我的问题的答案。 问题来了。

我有一个如下所示的包

package/
   __init__.py
   A/
      __init__.py
      foo.py
   test_A/
      __init__.py
      test.py

我在test.py中有一行:

from ..A import foo

现在,我在包的文件夹,我运行

python -m test_A.test

我收到消息

"ValueError: attempted relative import beyond top-level package"

但是如果我在包的父文件夹中,例如,我运行:

cd ..
python -m package.test_A.test

一切都很好。

现在我的问题是: 当我在包的文件夹中,我运行test_A子包中的模块作为test_A。测试,根据我的理解,..A只上升了一层,仍然在包文件夹中,为什么它给出消息说在顶层包之外。导致此错误消息的确切原因是什么?


当前回答

package/
   __init__.py
   A/
      __init__.py
      foo.py
   test_A/
      __init__.py
      test.py

在A/__init__.py中导入foo:


from .foo import foo

当从test_A/导入A/时


import sys, os
sys.path.append(os.path.abspath('../A'))
# then import foo
import foo

其他回答

这些解决方案在3.6中都不适合我,文件夹结构如下:

package1/
    subpackage1/
        module1.py
package2/
    subpackage2/
        module2.py

我的目标是从module1导入到module2。奇怪的是,最后对我有用的是:

import sys
sys.path.append(".")

注意单点解决方案,而不是迄今为止提到的两点解决方案。


编辑:以下内容帮助我澄清了这一点:

import os
print (os.getcwd())

在我的例子中,工作目录(出乎意料地)是项目的根目录。

package/
   __init__.py
   A/
      __init__.py
      foo.py
   test_A/
      __init__.py
      test.py

在A/__init__.py中导入foo:


from .foo import foo

当从test_A/导入A/时


import sys, os
sys.path.append(os.path.abspath('../A'))
# then import foo
import foo

这实际上比其他答案要简单得多。

TL;DR:直接导入A,而不是尝试相对导入。

当前工作目录不是包,除非您从另一个文件夹导入文件夹包。因此,如果您打算将包导入其他应用程序,那么包的行为将正常工作。不管用的是测试…

在不改变目录结构的情况下,只需要改变test.py导入foo.py的方式。

from A import foo

现在运行python -m test_A。test将在没有ImportError的情况下运行。

为什么会这样?

当前工作目录不是包,但它被添加到路径中。因此可以直接导入文件夹A及其内容。这是同样的原因,你可以导入任何其他包,你已经安装…它们都包含在你的路径中。

如果在上层文件夹中有__init__.py,可以将导入初始化为 导入文件/路径作为初始化文件的别名。然后你可以使用它在较低的脚本:

import alias

编辑:这个问题在其他问题中有更好/更连贯的答案:

兄弟包导入 第10亿次相对进口


Why doesn't it work? It's because python doesn't record where a package was loaded from. So when you do python -m test_A.test, it basically just discards the knowledge that test_A.test is actually stored in package (i.e. package is not considered a package). Attempting from ..A import foo is trying to access information it doesn't have any more (i.e. sibling directories of a loaded location). It's conceptually similar to allowing from ..os import path in a file in math. This would be bad because you want the packages to be distinct. If they need to use something from another package, then they should refer to them globally with from os import path and let python work out where that is with $PATH and $PYTHONPATH.

当你使用python -m package.test_A。测试,然后使用from ..import foo可以很好地解决问题,因为它跟踪了包中的内容,而你只是访问了加载位置的子目录。

为什么python不认为当前工作目录是一个包?不知道,但天哪,这将是有用的。