./helper.py
./caller1.py
./sub_folder/caller2.py
It's fine when importing helper.py
from caller1.py
.
caller1.py
from helper import hello
if __name__ == '__main__':
hello()
but when importing from ./sub_folder/caller2.py
with the exact same code I got the error...
ModuleNotFoundError: No module named 'helper'
I would like to organize files into sub-folders because the project is quite large.
You have to understand how Python finds the modules and packages when using import.
When you execute a python code, the folder in which this file is will be added to the PYTHONPATH which is the list of all the places where python will look for your packages and modules.
When you call caller1.py, it works because helper.py is in the same folder but it does not work for caller2.py because python does not find it in the same folder nor the other path in PYTHONPATH.
You have three options:
pip install -e
, this way python will be able to find your modules as they will be install in the site-packages of your python environment (most complex but cleanest solution)