python - 值错误: attempted relative import beyond top-level package python

标签 python importerror

我有这样的目录结构。

Chatbot/
   utils/
     abc.py
   projects/
      proj1/
        utils/
          __init__.py
          data_process.py
        components/
          class1.py

我的结构中有两个 utils 文件夹,一个位于顶层,一个位于我的项目文件夹内。

现在我想在 class1.py 中导入 data_process.py 文件。所以我尝试了这样的

from utils.data_process import DataProcess

但它引用了顶级 utils 文件夹,甚至 VSCode 也无法识别它。我尝试在 utils 文件夹中创建 __init__.py 文件,但仍然不起作用。

我尝试使用空的__init__.py,然后放置此内容

from . import data_process
__all__ = ['data_proces']

然后

from .data_process import DataPreprocess
__all__ = ['DataPreprocess']

然后我尝试了

from ..utils.data_process import DataProcess

VSCode 正在识别这一点,但它不起作用并抛出错误

ValueError: attempted relative import beyond top-level package

即使我尝试将名称 utils 更改为其他名称,但仍然存在相同的问题

我该如何解决这个问题?

最佳答案

Python 模块由一个名为 __init__.py 的特殊文件定义,并且该文件应该存在于所有子目录中。因此,您的文件结构将是:

Chatbot/
   __init__.py
   utils/
     __init__.py
     abc.py
   projects/
      __init__.py
      proj1/
        __init__.py
        utils/
          __init__.py
          data_process.py
        components/
          __init__.py
          class1.py
          class2.py

现在,您可以进行相对导入,例如:

  • 使用.导入同一目录中的内容。示例:
# file Chatbot/projects/proj1/components/class2.py
from .class1 import *
  • 同样,对于两级使用 ..,对于三级使用 ...,依此类推!

例如:

# file Chatbot/projects/proj1/components/class2.py
from ..utils.data_process import * # import from data_process.py
# there will be four "." earlier I made a counting mistake
from ....utils.abc import * # import something from abc.py

编码约定

在编写 python 模块/包时,您可能需要遵循 PEP8 Convention .

此外,我相信您正在尝试使用您的包 Chatbot 执行不同的项目,这是正确的吗?然后,最好为 Chatbot 设置 PYTHONPATH 并执行所有项目,并单独导入。

编辑:上传虚拟文件

即使使用两个 utils 目录,我也能够无缝地处理这个项目。项目结构:

enter image description here

main 文件及其输出:

# file main.py
from chatbot.utils.abc import hello as a1
from chatbot.projects.proj1.components.class1 import super_hello
from chatbot.projects.proj1.utils.data_process import hello as b1

print(a1(), b1())
print(super_hello())

enter image description here

同样,如果您在 PYTHONPATH 下有 chatbot,您可以从设备的任何位置调用该项目。

代码详细信息和文件为added into my github account了解详情。

关于python - 值错误: attempted relative import beyond top-level package python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68554755/

相关文章:

python - 为什么 pip freeze 返回一些 "gibberish"而不是 package==VERSION?

python - 在python中插入有界像素

Python:调整坐标

python - NumPy 或 SciPy 计算加权中位数

python - 在 C++ 中嵌入 Python : Importing modules in python script works during one function call but not another

python - ImportError:没有名为 extern 的模块

python - 在 Python 中接收 16 位整数

python - ImportError:无法从部分初始化的模块 'dcc' 导入名称 'dash' - python

python - ModuleNotFoundError : No module named 'sklearn.externals.six'

python - 导入azure.storage错误