Python相对导入。“试图在顶级包之外进行相对导入”

2024-04-19 04:09:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我有以下结构

└── 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)

定义的内容.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

那么我做错了什么


Tags: 文件项目frompyimport内容helloworld