0

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.

asked Sep 14, 2022 at 18:53

1 Answer 1

1

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.

answered Sep 14, 2022 at 19:01
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.