I want to import a module from a subpackage so I went here Relative importing modules from parent folder subfolder and since it was not working I read all the literature here on stack and found a smaller problem that I can reproduce but cannot solve.
I want to use relative imports because I don't wanna deal with sys.path etc and I don't wanna install every module of my project to be imported everywhere. I wanna make it work with relative imports.
My project structure:
project/
__init__.py
bar.py
foo.py
main.py
bar.py:
from .foo import Foo
class Bar():
@staticmethod
def get_foo():
return Foo()
foo.py:
class Foo():
pass
main.py:
from bar import Bar
def main():
f = Bar.get_foo()
if __name__ == '__main__':
main()
I am running the project code from terminal with python main.py
and I get the following:
Traceback (most recent call last):
File "**omitted** project/main.py", line 1, in <module>
from bar import Bar
File "**omitted** project/bar.py", line 1, in <module>
from .foo import Foo
ImportError: attempted relative import with no known parent package
Why am I getting this error? It seems that bar doesn't recognize project as the parent package but:
__init__.py
is in placebar.py
is being run as a module not a script since it is called from main and not from the command line (so__package__
and__name__
should be in place to help solve the relative import Relative imports for the billionth time)
Why am I getting this error? What am I getting wrong? I have worked for a while just adding the parent of cwd to the PYTHONPATH but I wanna fix this once and for all.