1

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

SagiZiv
  • 932
  • 1
  • 16
  • 38

1 Answers1

2

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

padu
  • 689
  • 4
  • 10
  • Hi, thanks for the answer. It solved the issue just like I wanted :-) Should I add that __init__.py file to every package in my project? – SagiZiv Aug 26 '21 at 10:46
  • Thank you, I'm glad. Mark then as the solution to the problem) This file should be added to all directories where there is an internal import. That is, if in the directory d appears script4.py and in script3.py you want to import as import script4 then you should add the \__init__.py file to the d directory – padu Aug 26 '21 at 11:00