Insert Python Packages from Separate Directory into a different Namespace

68 Views Asked by At

Suppose in my Python path, I had the namespace foo. I have modules in a separate directory (not in the python path) called bar: x.py, y.py, z.py. So the layout might look something like this:

|--/python/path/site-packages/foo/ 
|----__init.py__
|--...
|--/some/other/directory/bar/
|----__init__.py
|----x.py
|----y.py
|----z.py

So, given that foo is already in my path, I can easily do import foo. However, is there any sort of black magic I can add to that foo/__init__.py so that in my Python shell, I can start doing something like from foo import x or from foo.x import my_function? Ideally looking for a solution that works on both Python 2.7 and Python 3.6, but that isn't strict.

EDIT: I wanted to add that bar/ could also have sub-folders or sub-packages, in the ideal scenario.

1

There are 1 best solutions below

0
On BEST ANSWER

Forgot that I had asked this question here, but, in case anyone else ends up here, this is what I ended up doing.

# /python/path/site-packages/foo/__init__.py
__path__.append("/some/other/directory/bar/")

The __path__ for a particular namespace tells Python which directories that namespace should look at.