python - Python 相对导入。“尝试相对导入超出顶级包”
问题描述
我想在我的项目的根目录中有一个带有常量的文件。我正在尝试使用相对导入来解决这个问题。到目前为止我尝试过的是:
我有以下结构
└── project
├── packageA
│ ├── fileA.py # contains class A
│
└── definitions.py
└── main.py
文件A.py的内容
from ..definitions import hello_world
class A:
def __init__(self):
print(hello_world)
Definitions.py 的内容
hello_world = "Hello world"
main.py 的内容
from packageA.fileA import A
A()
我站在项目目录中并运行命令
python3 main.py
我收到以下错误
line 1, in <module>
from ..definitions import hello_world
ValueError: attempted relative import beyond top-level package
那么我在这里做错了什么?
解决方案
代替
from ..definations import hello_world
你可以使用
from definations import hello_world
推荐阅读
- java - 如何使用 Apache-POI 在 Excel 中计算公式并避免“保存更改”消息框?
- xml - 如何使用 XML 架构从共享点站点中删除链接
- javascript - 如何在 3rd 方应用程序中使 Slack 频道保持最新?
- python - 在不隐藏构造函数、可选参数或功能的情况下继承时避免使用长构造函数
- java - 如何为以下代码编写 junit 和 mockito
- assembly - 装配 Tricore 加载指令
- azure - Azure 函数 v2。无法从 nuget 引用 dll
- html - 更改多个特定数据的颜色
- php - php函数父返回
- javascript - SVG图案改变悬停元素的颜色