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:You can use:
These import statements become relative. The
"."allows Python to resolve the current package which ismodule1and this package is already imported and it can able to find it.Remember that Python will only recognize packages which are in the
sys.pathlist. Since you run thefile.pyfile, only its directory is going to be added to thesys.path, so Python can't findmodule1_file1directly. It has to find it throughmodule1. One way is to use absolute import (from module1.module1_file1 import foo), and the better one is the mentioned relative import.