从同一项目中的不同目录导入类

时间:2020-02-26 12:41:40

标签: python python-3.x python-import importerror

我有下一个目录结构:

.
├── models
│   ├── description.py
│   ├── identification.py
│   └── person.py
└── utils
    └── generators
        └── person.py

在导入models目录中每个文件中的类时遇到下一个错误:

Traceback (most recent call last):
  File "utils/generators/person.py", line 1, in <module>
    from models.person import Person
ModuleNotFoundError: No module named 'models'

这是我的utils/generators/person.py文件中的代码:

from models.person import Person
from models.identification import Identification
from models.description import Description

如何将这些类导入文件?

1 个答案:

答案 0 :(得分:0)

Python不在上层目录的后代目录中搜索导入的模块。

要消除此问题,您可以在根目录(您将其标记为点)中引入main.py,以将其导入公共名称空间。

在单独的注释上(如注释中所指出的那样),不再需要为Python 3.3+添加空的__init__.py文件(see this answer),因此对于Python 3而言,这不再是问题

相关问题