mayool
mayool

Reputation: 148

understanding hierarchical python modules & packages

I am trying to work with python packages and modules for the first time and come across some import errors I don't understand. My project has the following structure:

   upper
    ├── __init__.py
    ├── upper_file.py # contains "from middle.middle_file import *"
    └── middle
        ├── __init__.py
        ├── middle_file.py  # contains "from lower.lower_file import Person, Animal"
        └── lower
            ├── __init__.py
            └── lower_file.py # contains the Classes Person and Animal

I can run middle_file.py and can create inside the file a Person() and Animal() without any problems.

If I try to run upper_file.py I get a ModuleNotFoundError: No module named 'lower' error.

However, I have no trouble importing Animal() or Person() in upper_file.py directly with from middle.lower.lower_file import *

If I change the import statement inside middle_file.py from from lower.lower_file import Person, Animal to from middle.lower.lower_file import Person, Animal I can successfully run upper_file.py but not middle_file.py itself (and pycharm underlines the import in middle_file.py red and says it doesn't know middle)

In the end, I need to access inside of upper_file.py a class that is located inside of middle_file.py, but middle_file.py itself depends on the imports of lower_file.py.

I already read through this answer and the docs but just don't get how it works and why it behaves the way it does.

Thanks for any help in advance.

Upvotes: 0

Views: 74

Answers (1)

Felipe Pereira
Felipe Pereira

Reputation: 66

You should use relative import to accomplish this. First link on Google I found some practical example that could help you understand better.

On middle_file try to use from .lower.lower_file import *. It should solve the issue on upper_file.

Upvotes: 1

Related Questions