Import of my custom module could not be resolved

Question:

I’ve done some searching, but nothing either works or applies to this specific case.

I have a file structure like this:

- my_project
   - app.py
   - my_project
      - services
         - begin.py
         - data_analysis.py
         - model_creation.py
         - output.py

and I am trying to simply import each of the modules into the app.py file so I can run a flask application, but I keep getting an import with only one of the imports (and it is always the same one). For example, if I ran python app.py, I would get:

File "C:Usersmemy_projectapp.py", line 9, in <module>
    from my_project.services.data_analysis import analyze
ModuleNotFoundError: No module named 'my_project.services.data_analysis'

I would think it has to do with relative imports or something, only its just one of the files that is having the issue, not several/all of the files. Any ideas on why I’m getting this error?

EDIT: modified project structure.

EDIT 2: this is unique as when running app.py, it still allows for things such as from .my_project.begin import start or from my_project.model_creation import create, but no relative or non-relative import will work for just the data_analysis.py module.

Asked By: gwaugh

||

Answers:

add __init__.py files to your directories and subdirectories. It tells python to treat directories as modules.

example:


• my_project
   - app.py
   • my_project
      • services
         - __init__.py
         - begin.py
         - data_analysis.py
         - model_creation.py
         - output.py

In app.py:

from my_project.services.data_analysis import analyze 

I’m under the impression that services is a directory inside the second my_project folder. if it’s not, then you would import like so from services.data_analysis import analyze

Answered By: Jordan

My solution to this was to copy the module file that was causing the issue, and then deleting the original file and renaming the new one. This resulted in the error immediately going away.

Answered By: gwaugh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.