【问题标题】:ValueError: Attempted relative import in non-package - relative import in pythonValueError: Attempted relative import in non-package - python中的相对导入
【发布时间】:2020-06-30 00:49:23
【问题描述】:

文件夹目录为:

server/
    |_entities.py
    |_config.py

在我的 entity.py 文件中,我有以下内容:

from .config import config

但是当我调试的时候,会出现以下问题:

File "entities.py", line 14, in <module>
from .config import config
ValueError: Attempted relative import in non-package

【问题讨论】:

标签: python python-3.x


【解决方案1】:

确保您在服务器目录中有一个__init__.py。这是使 Python 将包含该文件的目录视为包所需的空文件。

那就试试from server.config import config

Server 是包的顶级名称。

来自docs

包是一种构造 Python 模块命名空间的方法,使用 “带点的模块名称”。例如,模块名称 A.B 指定一个 名为 A 的包中名为 B 的子模块

您还应该考虑将变量 config 重命名为其他名称,以免与名为 config 的文件混淆。

【讨论】:

    猜你喜欢
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    相关资源
    最近更新 更多