I am sure the question might seem pretty stupid, but searching around didn't yield me much result, so a redirection towards a response would be quite welcome.
So, I have a Python project with nested modules:
src
|-package_1
|-__init__.py
|-module_1_1
|-module_1_2
|-package_2
|-__init__.py
|module_2_1
|module_2_2
|-main_module
|-__init__.py
From the main_module
I import the contents of package_2
and from modules inside package_2
I import contents of package_1
modules with the similar statements:
(main_module
)
from package_2.module_2_1 import foo
(module_2_1
)
from package_1.module_1_1 import bar
It all works well as a long as I run
Python main_module
but as soon as I try to run, for instance to use a function of the module_2_1
on it's own
Python module_2_1,
if fails with a message that it could not resolve the following import:
from package_1.module_1_1 import bar
From my understanding, Python is not aware of where it should go look for package_1, because it is not aware of where the project root is.
As a remedy, I am currently pre-pending the following line to all the inner modules to properly resolve the import:
if __name__ == "__main__":
import os
os.chdir("..")
But it just don't feel right.
What would be the correct way of solving this problem?