0

My project directory has this structure:

src
 |__model
      |___models.py
      |___ prepare_data.py
 |_utils.py

models.py imports a function from prepare_data.py, which imports a function from utils.py.

When I run the script from bash, if I'm in the model folder the command is: python models.py and I get the error: ModuleNotFoundError: No module named 'utils'

If instead I run the command from the src folder with python model/models.py the error I get is ModuleNotFoundError: No module named 'prepare_data'

I know that moving utils.py in the model directory would fix the problem but I don't want to do that. I tried using the -m argument with dotted notation. So the second command becomes: python -m model.models, but I still get the same error. What can I do to fix it?

EDIT: I also tried putting an empty __init__.py file in the root directory but it didn't fix the problem

EDIT 2: I solved the problem by typing this at the beginning of the model.py module, as suggested in this answer:

import sys
sys.path.append('../')

2 Answers2

0

Try creating an empty __init__.py file in the root of your directory https://docs.python.org/3/tutorial/modules.html#packages

That lets python know it should treat the contents as a package.

LTJ
  • 1,197
  • 3
  • 16
  • In Python 3 directories are more-or-less automatically treated as packages. The problem is if you run a module in a package directly it won't be able to resolve the package structure properly. If you want to make a file in your package executable there needs to be a `__main__.py` module somewhere. – Iguananaut Oct 07 '22 at 12:58
  • I created the file, but the problem persists –  Oct 07 '22 at 16:40
0

From source folder run the command and the error you are saying ModuleNotFoundError: No module named 'prepare_data' You are using it like this:

import prepare_data

But now use:

import model.prepare_data
  • I just found an alternative solution to my problem, but also your solution would have worked. I don't know why I didn't think about that since I had already done that in the past –  Oct 07 '22 at 17:08