[英]Importing classes from different directory within the same project
I have the next directory structure:我有下一个目录结构:
.
├── models
│ ├── description.py
│ ├── identification.py
│ └── person.py
└── utils
└── generators
└── person.py
I'm getting the next error while importing the classes in each file that exist within the models
directory:我在导入
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'
And this is the code in my utils/generators/person.py
file:这是我的
utils/generators/person.py
文件中的代码:
from models.person import Person
from models.identification import Identification
from models.description import Description
How can I import those classes in my file?如何在我的文件中导入这些类?
Python does not search for modules on import in the directories that are descendants of the upper-level directories. Python 不会在上级目录的后代目录中搜索导入时的模块。
To eliminate this problem you can introduce a main.py
in the root (you marked it as dot) that would do the imports into the common namespace.为了消除这个问题,您可以在根目录中引入一个
main.py
(您将其标记为点),它将导入公共命名空间。
On a separate note, as wisely pointed out in the comments, it is no longer necessary to add empty __init__.py
files ( see this answer ) for Python 3.3+ so this cannot be the issue for Python 3.另外,正如评论中明智地指出的那样,不再需要为 Python 3.3+ 添加空的
__init__.py
文件(请参阅此答案),因此这不是 Python 3 的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.