Search code examples
gitpython-3.xgit-submodules

how to utilize submodule without any modification in python?


I'm supposed to make two git repositories and make one of these a submodule. I have not to modify anything in the submodule. But, when I try to import something in the submodule, there are some path problem. The problem is as follows.

Module 1 (git repository)

layout

module
  |
  +--- __init__.py
  +--- model.py
  +--- utils.py

in model.py

import utils

# blah, blah

Module 2 (git repository)

The second module uses model.py the first module

layout

module
  |
  +--- main.py
  +--- submodule (Module 1 repository)

in main.py

import submodule.model

# blah, blah

< command line >

~/module2$ python main.py

Then, There is a crash.

----> 1 import submodule.model
      2 
      3 # blah, blah

~/module2/submodule/model.py in <module>()
----> 1 import utils
      2
      3 # blah, blah
ImportError: No module named 'utils'

The "Module 1" is required not to be modified. then, how can I use this submodule in the "Module 2"?


Solution

  • In Python 3 all imports are absolute. Module1 must perform absolute import

    import module1.utils
    

    or relative import explicitly:

    import .utils
    

    It's a bug in Module1 and you should fix it.

    If you still insist on using a buggy module, you can add Module1 to sys.path or PYTHONPATH so that import utils finds it in sys.path.