Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import python file from 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

like image 801
pedrorijo91 Avatar asked Apr 20 '15 11:04

pedrorijo91


People also ask

Is using Git submodules a good idea?

Git submodules may look powerful or cool upfront, but for all the reasons above it is a bad idea to share code using submodules, especially when the code changes frequently. It will be much worse when you have more and more developers working on the same repos.

What is the .gitmodules file?

The . gitmodules file, located in the top-level directory of a Git working tree, is a text file with a syntax matching the requirements of git-config[1]. The file contains one subsection per submodule, and the subsection value is the name of the submodule.

What is recurse submodules Git?

If you pass --recurse-submodules to the git clone command, it will automatically initialize and update each submodule in the repository, including nested submodules if any of the submodules in the repository have submodules themselves.


2 Answers

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.

like image 102
paddyg Avatar answered Sep 16 '22 16:09

paddyg


I am used to avoiding modifying sys.path.

The problem is, when using git submodule, submodule is a project directory, not a Python package. There is a "gap" between your module and that package, so you can't import.

Suppose you have created a submodule named foo_project, and there is a foo package inside.

. ├── foo_project │   ├── README.rst │   └── foo │       └── __init__.py └── main.py 

My solution will be creating a soft link to expose that package to your module:

ln -s foo_project/foo foo 
. ├── foo_project │   ├── README.rst │   └── foo │       └── __init__.py ├── foo -> foo_project/foo └── main.py 

Now you can import foo in the main.py.

like image 42
Kevin Avatar answered Sep 18 '22 16:09

Kevin