I´ve the following project structure:
|- main.py
|- lib/
|- foo.py
|- bar.py
Example code main.py
from lib.foo import foo
from lib.bar import bar
def main():
bar()
foo()
if __name__ == '__main__':
main()
Example code lib/bar.py
def bar():
# do something
Example code lib/foo.py
from .bar import bar
def foo():
bar()
if __name__ == '__main__':
foo()
Now the problem: If I execute the main.py everything is working fine. If I execute foo.py I get the following python error:
ImportError: attempted relative import with no known parent package
I found a similar problem on this Thread and this comment fixed my problem so far: https://stackoverflow.com/a/45556023/4428711
Solution so far for foo.py:
try:
from bar import bar
except ImportError:
from .bar import bar
def foo():
bar()
if __name__ == '__main__':
foo()
Now my question: Is there a better solution for nested relative imports than this regarding direct and indirect executions?