I am Having problems understanding the import system in python.
for the sake of this question the program is structured like this:
**Demo
-- tests
____ __init__.py
---- test_1.py
---- test_2.py
-- main.py**
I have grasped the basic functioning of importing, and everything works fine when I’m working with modules within the same package.
In the above program I created a simple function inside test_2.py called hello:
def hello():
print("hello")
and I’ve imported into test_1.py:
from test_2 import hello
everything works fine so far, but I get stuck I try to import test_1.py into main.py (which is outside of the package) like this:
from tests import test_1
this throws the following error:
ModuleNotFoundError: No module named 'test_2'
Now, I understand that this error is occurring because Python reads the entire module when it is imported, therefore it tries to execute the import statement and it fails to find the path to test2 (because it is not in the same package).
I was thinking to just put all my code in one module, so I don’t have to use any imports within the package and therefore the code should not break if i import that package elsewhere, but this cant be the solution…
I’m sure this is a very basic question so I’ve spent many hours reading python’s documentation and surfing the internet, before coming here.
I’ve come across different importing strategies like: sys.path, importlib or PYTHONPATH, but i don’t think i fully understand the concepts behind those.
Riccardo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.