Pycharm imports from Git Submodule
Asked Answered
A

2

8

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!

Adrianople answered 19/6, 2020 at 4:36 Comment(0)
H
2

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.

Heald answered 3/8, 2020 at 15:15 Comment(0)
S
0

Your package name should NOT contain dash.

The issue is due to the naming of your package contains "-" dash, which is NOT allowed in python. So you can never import git-submodule-repo . git-submodule-repo is not an identifier. rename the submodule to git_submodule_repo, you will be able to import it just like a normal package.

So this has nothing to do with pycharm neither with submodule.

Scabby answered 21/3, 2021 at 15:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.