Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I transparently redirect a Python import?

I'm looking for a way to emulate symlinks for Python imports. I'd like to be able to unzip the following folder structure in-place without duplicating files:

root
├─ python_lib
│  └─ my_utils
│     ├─ __init__.py
│     └─ etc.py
├─ app1
├─ app2
└─ app3
   ├─ lib
   │  ├─ __init__.py
   │  └─ my_utils.py
   └─ run.py

app3/run.py contains this:

from lib.my_utils import etc

etc.pancakes()

I'd like the code to use the etc located in python_lib/my_utils/. Is there anything I can put in app3/lib/my_utils.py so that Python >= 3.1 will transparently import the python_lib/my_utils/ folder (using relative paths and ..), and subpackages will also work?

like image 960
zildjohn01 Avatar asked Jan 31 '11 20:01

zildjohn01


People also ask

How do you redirect a path in Python?

The way that url_for() works is instead of redirecting based on the string representation of a route, you provide the function name of the route you want to redirect to. So if we update the code to the snippet here, we get the same result but using url_for() instead of redirect().

How do you set a path to import in Python?

append() Function. This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.


2 Answers

You will have to execute something before app3/run.py reaches the import statement.

import python_lib
import sys
sys.modules['lib'] = python_lib
# ...
from lib import etc
print etc.__file__
print dir(etc)
like image 180
Apalala Avatar answered Nov 01 '22 11:11

Apalala


You should add this path into sys.path. For example:

lib_path = os.path.abspath( os.path.split( os.getcwd()+"/"+sys.argv[0] )[0]+"/../_lib/my_utils/" )
sys.path.append(lib_path)
like image 43
Elalfer Avatar answered Nov 01 '22 12:11

Elalfer