Python import ModuleNotFoundError

I have a Python project that I am working on my local PC using PyCharm, and I execute the code from Google Colab server (because I need the GPU).

I get my project to Colab using GitHub (I upload the package to GitHub and than clone it in Colab).

However, I have problem with imports.

The package structure is like this:

a/
->b/
  ->c/
    -> script1.py
    -> script2.py
  ->d/
    -> script3.py

script1.py imports script2.py and script3.py.

I try import like that:

import script2
from b.d import script3

This is my test cases:

  • Locally on my PC, the main script is in folder a

  • Remotely on Google Colab, where the main script is the notebook (which is outside of folder a obviously).

In both this cases I get ModuleNotFoundError for my imports.

But if I use relative imports like so:

from . import script2
from ..d import script3

It works great in both of the above cases, but PyCharm complains about relative imports and the script would only execute when the main is outside folder b.

I tried adding __init__.py to folder d, but to be honest I still don’t fully understand the purpose of this files. And from what I read they are redundant in Python 3.3+ (I use Python 3.7).

So my question is: How can I make the imports work anytime no matter the location of the main script?

Thanks in advance

Answer

here it is perfectly explained what is the absolute and relative import of modules and how to work with them. In your case, to do without relative import in the c folder, create the file __init__.py with the following contents:

import os, sys

sys.path.append(os.path.dirname(os.path.realpath(__file__)))

Then you will be able to inside script1.py leave it

import script2
from b.d import script3

And this import will work outside of the folder with