Import python from a subdirectory in a safe git way

Here is my current directory structure:

proj/ proj/__init__.py proj/submodFolder/ proj/submodFolder/submod/ proj/submodFolder/submod/__init__.py 

I am writing a project and I would like to have import submod or even import submodFolder.submod in proj/__init__.py . However, without __init__.py in submodFolder, this will not work.

Suppose subodFolder is a git repository that I have sub-repoed (if you have a third-party library); adding the required __init__.py will break the git subrepo submode and complicate updating libraries from their main repositories.

Assuming submodFolder is the immutable sub-repo of git, what is the best way to push python to the dirtree method of the module? Modifying the python path seemed the closest solution to me, but none of the questions asked already accepted an immutable subodFolder.

Examples are welcome, mark the relative paths.

+4
source share
1 answer

If you do not want to change the PYTHONPATH environment variable, you can change sys.path inside proj / __ init__.py, the following should work:

 import sys import os sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'submodFolder')) import submod 

Step-by-step code with comments, so it makes a little more sense:

 # get absolute path to proj/__init__.py script_path = os.path.realpath(__file__) # strip off the file name to get the absolute path to proj proj_path = os.path.dirname(script_path) # join on os.sep to get absolute path to proj/submodFolder submod_path = os.path.join(proj_path, 'submodFolder') # add the complete path to proj/submodFolder to sys.path sys.path.append(submod_path) 
+2
source

All Articles