Receiving Import Error: No Module named ***, but has __init__.py

If anybody lands here:

I encountered this error as well. In my case, I used ~/my/path/ at the path.sys.append(...), and the fix was replacing ~ with the explicit path name (you can inquire it if you type pwd when you are on linux shell, or use os.path.expanduser(..) )


Just a note for anyone who arrives at this issue, using what Gus E showed in the accept answer and some further experience I've found the following to be very useful to ensure that I can run my programs from the command-line on my machine or on another colleague's should the need arise.

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "..", ".."))

When I execute the 'main' method, which is located in the 'nested' directory, it ensures that the 'src' directory is added to the PYTHONPATH at the time of execution meaning all following imports will not throw an error.

Obviously, you need to adjust the number of ".." arguments to the os.path.join() method as determined by the location in your program of where your main method is executed from


Try adding a sys.path.append to the list of your imports.

import sys
sys.path.append("/Project/src/")
import root
import root.nested.tests

Yet another way to solve this without the path goes like this: consider the following code where inside your folder name 'app' you have 3 files x.py, y.py and an empty init.py. So to run x.py you have an import from y such that:

x.py

from app.y import say_hi
print ("ok x is here")
say_hi()

And

y.py

print ("Im Y")
def say_hi():
    print ("Y says hi")

so the folder structure would look like this:

testpy
       app
           __init__.py
           x.py
           y.py

Solution: in the folder BEFORE app do the following:

$ python -m app.x

Note: I did not use x.py (simply app.x)

Result:

Nespresso@adhg MINGW64 ~/Desktop/testpy
$ python -m app.x
Im Y
ok x is here
Y says hi