0

This is a follow up question for a question I asked not long ago. The answer is correct and works great, but when I tried to apply it to the main package it didn't work.

Lets say I have the following files structure:

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

(The __init__ files are just like in the answer I linked above).

And in script3.py I import script1.py like so: from b.c import script1.

It works when I run it in Pycharm, but when I clone the repository in Colab (all this code is in a GitHub repository) I get the error: ModuleNotFoundError: No module named 'b'

Which makes sense because my package is not in the sys.path variable. And adding the folder a to the sys.path manually, after I cloned the repository, helps but it is not a real solution because I can't always do it (e.g. in unit-tests).

So my question is, how can I fix it¿ Adding the __init__ file to folder b didn't help.

Notes:

  1. Folder a is the project's folder, so it is not part of the path.
  2. My GitHub repository is private, so I am not sure if making it installable (by adding setup.py and all that) would be helpful, but its my first time so I am not sure.
  3. In Colab I import script3 like so from a.b.d import script3. In this case I must specify folder a because, again, b is not in sys.path.
  4. As I mentioned above, I can manually fix it in Colab but it doesn't really solves the issue, because if I want to run unit-tests for example it won't work.
2
  • How are you running your code? python d/script3.py or python b/d/script3.py? Did you try to configure PYTHONPATH env variable in Colab? Commented Sep 29, 2021 at 23:02
  • @EmidioNeto Thanks, I have added 2 more notes to my question Commented Sep 29, 2021 at 23:11

1 Answer 1

1

You can backwardly add folder b to your path and then import only from c folder, like this:

from os.path import realpath, dirname import sys sys.path.append(dirname(dirname(realpath(__file__)))) from c import script1 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.