How to resolve "ValueError: attempted relative import beyond top-level package"

How to resolve "ValueError: attempted relative import beyond top-level package"

我的项目有以下问题,请帮助我!这是我的包的结构:

/pkg

/pkg/__init__.py
/pkg/sub1/__init__.py
/pkg/sub2/__init__.py

/pkg/sub1/foo1.py
/pkg/sub2/foo2.py

这里是 foo1.py 的实现:

from ..sub2 import foo2

def f():
    print("Hello!")

当我 运行 foo1 时出现错误:ValueError: attempted relative import beyond top-level package.

我可以通过以下调整解决它:

import sys
import os
sys.path.append(os.path.abspath(os.path.pardir))

from sub2 import foo2
def f():
    print("Hello!")

但我想知道是否有一种方法可以不导入 sys 并在其中附加父目录。

我听说如果我有 .py 文件 '/pkg/start.py' 例如它调用了我的 foo1 模块,那么两个点就可以了。但是,有什么方法可以直接从foo1调用foo2吗?

在我看来,如果不将 pkg 添加到我的 PATH 中,就不可能从 sub1 中的 sub2 导入模块。原因如下:

Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

Here is official python web site, where it is explained