I have the structure
main.py from mymodule import a; a.A()
mymodule/
mymodule/__init__.py (empty)
mymodule/a.py # works when called from main.py, fails when called alone
mymodule/b.py class B: pass
mymodule/c.py class C: pass
mymodule/test.py from .a import A; A() # failing when called alone
In a.py there is:
from .b import B
from .c import C
class A:
def __init__(self):
self.b = B()
self.c = C()
if __name__ == '__main__':
A()
Calling main.py works perfectly. It calls a.py which does from .b import B.
But calling a.py alone fails on the same from .b import B with:
ImportError: attempted relative import with no known parent package
I have already read Relative imports in Python 3 and many similar questions such as How to import the class within the same directory or sub directory? but here this question is specific on:
Why does from .b import B succeed in a.py when called from main.py, and fails when called from a.py alone, or when calling test.py?
How to be able to have a test.py in the same directory than a.py and be able to import the latter? (without sys.path.append hacks)