Search code examples
pythonimportmodule

Python Error: Module not found even with module import


I have an issue related a module imports.

For example, I have the following file structure:

main_folder -> src -> main.py and logic.py

main_folder -> test -> tests_logic.py

The tests is for pytest file, I'm importing the other 2 files to the test, using for example:

from main_file.src.main import something

from main_file.src.logic import something

The issue is that every time I run the test file, the error ModuleNotFoundError: No module named appears, even with the right imports for the modules in the test file.

How can I solve this?

I tried to refactor the repo, setup environment. The only thing that works is if I put all the .py files in the same directory, without subfolders.


Solution

    1. for main_folder and src, make sure they have an __init__.py file (an empty file is sufficient)
    2. make sure that the parent directory of main_folder is included in sys.path before the import statement is executed. For example:
    import sys
    sys.path.append('/path/to/parent')
    
    from main_file.src.main import something
    from main_file.src.logic import something
    

    Note that there are more ways to configure sys.path. The example I gave might not be the most appropriate for your usecase.