I have a directory structure that looks like the following;
file.py
module1/
__init__.py
module1_file1.py
module1_file2.py
Lets say module1_file1.py
has a function foo
and module1_file2.py
has a function bar
.
I want to be able to import these functions into file1.py
, but instead of;
from module1.module1_file1 import foo
from module1.module1_file2 import bar
I want to be able to write;
from module1 import foo, bar
How do I go about doing this? I suppose I need to write something in the __init__.py
so that the functions can be accessed directly from module1
?
I tried adding the following to __init__.py
from module1_file1 import foo
from module1_file2 import bar
But this gave me the following error
ModuleNotFoundError: No module named 'module1_file1'
Inside __init__.py
, instead of:
from module1_file1 import foo
from module1_file2 import bar
You can use:
from .module1_file1 import foo
from .module1_file2 import bar
These import statements become relative. The "."
allows Python to resolve the current package which is module1
and this package is already imported and it can able to find it.
Remember that Python will only recognize packages which are in the sys.path
list. Since you run the file.py
file, only its directory is going to be added to the sys.path
, so Python can't find module1_file1
directly. It has to find it through module1
. One way is to use absolute import (from module1.module1_file1 import foo
), and the better one is the mentioned relative import.