0

Let's assume I have a Python package structure that looks like this:

MyModule
|
|-- app
    |
    |-- __init__.py
    |
    |-- main.py
    |
    |-- subpackage
        |
        |-- __init.py
        |
        |-- submodule1.py
        |
        |-- submodule2.py

Now, the idea is that the subpackage shall be closed as one entity within the project. Therefore, if the submodules depend on each other, one has something like, for instance, as code in the submodule1:

from submodule2 import somefunction as sf

My intuition would be that subpackage does not know, and does not need to know, anything about the upper-level such as main or the project it is in. However, if, in the main.py, I do something like

import subpackage.submodule1

I get the error ModuleNotFoundError: No module named 'submodule2'. Can somebody explain this behavior? I guess that, once an entrypoint script is defined, each path resolution starts from there?

How can I explicitly prevent this from happening (and keep the subpackage within this project structure)? Because, imagining that I have yet another module which is not on the same level as main.py from which modules of the subpackage need to be imported, there will be a conflict of path resolution.

With "prevent", I mean that I can still use the import statements as shown in the subpackage, and call subpackage modules from anywhere else without breaking anything.

cwellm
  • 64
  • 7
  • Does this answer your question? [Relative imports in Python 3](https://stackoverflow.com/questions/16981921/relative-imports-in-python-3) – BeRT2me Sep 25 '22 at 07:26
  • @BeRT2me Thanks for the reply and the hint for relative imports. But nah...it does not really solve the problem. It seems that relative imports somehow do the trick of enabling to use imports both from my main.py, as well as within the subpackage, but this seems to be ugly and error-prone (and maybe not the way as it is intended to be). – cwellm Sep 26 '22 at 07:24

0 Answers0