I have read a ton of stackoverflow answers and a bunch of tutorials. In addition, I tried to read the Python documentation, but I cannot make this import work.
This is how the directory looks like:
myDirectory ├── __init__.py ├── LICENSE ├── project.py ├── README.md ├── stageManager.py └── tests ├── __init__.py └── test_project.py There is a class in project.py called Project, and I want to import it in a file under tests directory. I have tried the following:
Relative import:
from ..project import Project def print_sth(): print("something") This gives me the following error: (running from the tests directory as python test_project.py and from myDirectory as python tests/test_project.py)
Traceback (most recent call last): File "test_project.py", line 1, in <module> from ..project import Project SystemError: Parent module '' not loaded, cannot perform relative import Absolute import with package name:
If I have something like the following, I get ImportError (with the same run command as above).
from project import Project def print_sth(): print("something") ------------------------------------------------------ Traceback (most recent call last): File "test_project.py", line 1, in <module> from project import Project ImportError: No module named 'project' and this too:
from myDirectory.project import Project def print_sth(): print("something") ------------------------------------------------------ Traceback (most recent call last): File "test_project.py", line 1, in <module> from myDirectory.project import Project ImportError: No module named 'myDirectory' Finally, I tried adding the if __name__ == '__main__' statement within the test_project.py file, but it still failed. I would really appreciate if anyone could help. If there is a solution where I do not have to write a verbose command, I would prefer that.
from project import Projectwithout the leading..? Python imports are related to folder structure, but they are not the folder structure and having the leading dots makes it skip the next module up, which is the one you want.