Git submodule's local import error - Python

Viewed 643

I'm working on a Python project (Project A) that uses another project from GitHub (Project B). I'm not a Git expert, so after a quick research, I found out that I should use the Project B as a git submodule.

So, I cd project_A_root and did the following:

git submodule add project_B
git submodule init
git submodule update

Now, my project structure looks like this:
enter image description here

In main.py file, I've imported a method from do_something.py.

main.py

from ProjectB.do_something import foo

However, do_something.py file imports a method from util.py file, and that's where the problem occurs.

do_something.py

from util import bar

Project B is a submodule and it assumes that Project B dir is the root of the project, so method from util.py in do_something.py is imported without specifying the package, and I'm getting an error:

ImportError: cannot import name 'bar' from 'util'

Instead, it should be imported like this:

from ProjectB.util import bar

I'm not sure what is the best way to handle this. I've fixed imports in submodule manually, but I cannot push that changes to Git because that's not how the submodules work, so if anyone wants to clone Project A, they must fix imports manually too.

Any help is welcome.

2 Answers

Try this in the head of main.py:

import sys
sys.path.append("ProjectB")

#### your old code ###
....

Git is just a version control system. Unfortunately, you can't handle this correctly. The possible solution is patching sys.path variable by adding the ProjectB directory, but this is hack. The best you can do is to use a Python packaging system, to package ProjectB into a pip package and install it as a usual package by pip. Usefull links:

Related