【问题标题】:Python relative imports. "Attempted relative import beyond top-level package"Python 相对导入。 “尝试相对导入超出顶级包”
【发布时间】:2021-08-16 09:07:35
【问题描述】:

我想在我的项目的根目录中有一个包含常量的文件。我正在尝试使用相对导入来解决这个问题。到目前为止我尝试过的是:

我有以下结构

└── project
    ├── packageA
    │   ├── fileA.py # contains class A
    │
    └── definitions.py
    └── main.py

fileA.py 的内容

from ..definitions import hello_world

class A:
    def __init__(self):
        print(hello_world)

defines.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

那么我在这里做错了什么?

【问题讨论】:

    标签: python


    【解决方案1】:

    而不是

    from ..definations import hello_world
    

    你可以使用

    from definations import hello_world
    

    【讨论】:

      猜你喜欢
      • 2020-04-06
      • 2020-11-03
      • 2017-02-22
      • 2021-10-03
      • 2016-05-12
      • 1970-01-01
      • 2020-03-07
      相关资源
      最近更新 更多