Search code examples
pythongit-submodulespython-import

How to import from a Python file in Git submodule


I've a project which uses Git submodules. In my Python file, I want to use functions from another Python file in the submodule project.

In order to work, I had to add the __init__.py file to all subfolders in the path. My folder tree is the following:

myproj
├── gitmodules
│   ├── __init__.py
│   ├── __init__.pyc
│   └── mygitsubmodule
│       ├── __init__.py
│       ├── __init__.pyc
│       └── file.py
└── myfile.py

Is there any way to make it work without touching mygitsubmodule?

Thanks


Solution

  • you can add to sys.path in the file you want to be able to access the module, something like:

    import sys
    sys.path.append("/home/me/myproj/gitmodules")
    import mygitsubmodule
    

    This example is adding a path as a raw string to make it clear what's happening. You should really use the more sophisticated, system independent methods described below to determine and assemble the path.

    Also, I have found it better, when I used this method, to use sys.path.insert(1, .. as some functionality seems to rely of sys.path[0] being the starting directory of the program.