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.
You should be running your project from the parent of project dir as:
$ python -m project.main # note no .py
This tells python that there is a package named project
and inside it a module named main
- then relative and absolute imports work correctly - once you change the import in main in either of
from .bar import Bar # relative
from project.bar import Bar # absolute