I'm having problems understanding the way import
, absolute and relative, works in Python.
I'll reproduce my working directory and omit some files for brevity:
A/
B/
__init__.py
main.py
C/
__init__.py
module1.py
module2.py
main.py
needs f1
and f2
from module1.py
. module1.py
needs f3
from module2.py
.
After tinkering and reading documentation I got to import functions to my main.py
file from my module1.py
file. I had to do the following inside main.py
:
from .C.module1 import f1, f2
.
module1.py
depends on functions from module2.py
. That is trivial: inside module1.py
:
from module2 import f3
.
This way I can call module1.py
directly and it will load f3
; however, in my main.py (which is a Flask app, by the way), it won't load, because module1.py
throws ModuleNotFoundError: No module named 'module2'
. I think that has to do with the fact that I'm in a different directory now. Anyways, if in module1.py
I change from module2 import f3
to from .module2 import f3
, main.py
will work, but then I can't call the module1.py
file directly because it will throw an ModuleNotFoundError: No module named '__main__.module2'; '__main__' is not a package
exception.
EDIT: accidentally swapped names.
Notice that I have __init__.py
in both directories/packages. What should I do so that both main.py
and module1.py
work?