首页 > 解决方案 > 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

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

标签: python

解决方案


代替

from ..definations import hello_world

你可以使用

from definations import hello_world

推荐阅读