0

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?

Metabinary
  • 171
  • 1
  • 2
  • 11
  • This difference in behavior is because the package `__main__` is special: https://stackoverflow.com/q/14132789/1032785 – jordanm Apr 13 '20 at 21:52
  • Yes, this was one of my first search results. BrenBarn explained it pretty amazing. I understand why this error appears and how to avoid it by running it with the -m tag as a module and not as a script. But how could I handle it for automate testing? This is my major problem. – Metabinary Apr 13 '20 at 22:11

1 Answers1

0

create file __init__.py in lib directory

from .foo import *
from .bar import *

Example code main.py

import lib

if __name__ == '__main__':
    lib.foo()

Example code lib/foo.py

import lib

def foo():
    lib.bar()

foo()
big-vl
  • 134
  • 1
  • 7