简体   繁体   中英

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:

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:

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM