Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pycharm imports from Git Submodule

I have a python project in Pycharm, wherein there is a nested Git submodule. Here is the folder structure:

my-git-repo
    git-submodule-repo
        package1
           foo.py
           bar.py
    package2
        baz.py
    .gitmodules

The imports in git-submodule-repo are structured as follows:

foo.py:
from package1.bar import some_func

However, Pycharm doesn't recognize this and wants me to instead have the following:

foo.py:
from git-submodule-repo.package1.bar import some_func

This is problematic because I don't want to have to change all the imports in git-submodule-repo (doesn't seem like good practice and isn't scaleable) and git-submodule-repo has dashes in it which isn't valid Python syntax for an import (I can't rename the repo).

I also need a way to import from git-submodule-repo in my code. Something like this:

baz.py:
from git-submodule-repo.package1.bar import some_func

But of course without the dashes making it invalid syntax. Here is the content of .gitmodules in case its useful:

[submodule "git-submodule-repo"]
    path = git-submodule-repo
    url = https://github.com/SomeAccount/git-submodule-repo.git

Any help would be appreciated!

like image 777
Amaar Avatar asked Jun 19 '20 04:06

Amaar


People also ask

How do I clone a submodules repo?

The list of steps required to clone a Git repository with submodules is: Issue a git clone command on the parent repository. Issue a git submodule init command. Issue a git submodule update command.

Does git pull pull submodules?

Once you have set up the submodules you can update the repository with fetch/pull like you would normally do. To pull everything including the submodules, use the --recurse-submodules and the --remote parameter in the git pull command .


1 Answers

Soultion 1
Use native PyCharm support by marking you submodule folders as Sources in Preferences -> Project -> Project Structure.
The drawback of this approach is that it will not allow you to run your code without PyCharm (e.g. from terminal on a remote server) unless you use PyCharm remote interpreter option (works in PyCharm Professional only).

Solution 2
Check out the solution proposed by @Kevin about general import of python files from git submodule. You may create soft link to the lib on interest in the root of the project. In your case the command will be:
$ ln -s git-submodule-repo.package1 package1
Then you will be able to import it with from package1.bar import some_func from foo.py.
The drawback of this approach is that it is not cross-platform e.g. you will not be able to run it from windows in case you need it.

like image 105
snk4tr Avatar answered Jan 04 '23 14:01

snk4tr