This is a common problem with the python import system, but one way to make it more manageable may be to define some imports in another __init__.py
in your projects root directory, which will create a separate namespace for your package and all subdirectories.
The way I setup the directories to reproduce your error is this structure:
Root directory: /package
:
/package
/package/__init__.py
/package/a
/package/a/__init__.py
/package/a/b
/package/a/b/__init__.py
/package/a/b/module1.py
/package/c
/package/c/__init__.py
/package/c/module2.py
In package/__init__.py
put the top-level module imports:
from a.b import module1
and then the only change I made is to module2.py
to contain only this function for testing:
from package import a # import top-level module from root package
def func():
a.b.module1.some_object() # call function of module1 from module2 (this module).
if __name__ == '__main__':
func()
then in the top-level root of the package, from terminal you should be able to run module2.py
:
$ python package/c/module2.py
should print out:
from a.b.module1: some object
Improvement and refinements can be made to get the exact behavior you desire.
For reference, I used this answer's suggestions: How to avoid circular imports in Python?