Pages

Tuesday, March 6, 2012

Redirect a Python Import

Problem:
You need to redirect a Python import to a module or package in a relative location.

Solution:
Create a dummy module that replaces its own reference in sys.modules with a reference to a module or package in another location.
# Paste this in the module being imported, in this example a package
# Note that when del sys.modules[__name__] is executed, local variables no longer accessible
# You can store items in sys.argv if exec('import {0}'.format(module_name)) needed,
# but you get the following warning:
# RuntimeWarning: Parent module 'attila' not found while handling absolute import
import os
import sys

RELATIVE_VALUE = -1  # Directories to step up:  -1 = . (packages only), -2 = .. , -3 = ... , etc.
PATH_APPEND = []  # After step up, append this sub path, example: ['foo', 'bar'] -> /foo/bar is appended

pth = os.path.sep.join(__file__.split(os.path.sep)[0:RELATIVE_VALUE] + PATH_APPEND)
sys.path.insert(0, pth)

del sys.modules[__name__]
import foo  #name of this module, and the one you are redirecting to


Reference: 

  1. http://stackoverflow.com/questions/4855936/how-can-i-transparently-redirect-a-python-import/9450785#9450785 
  2. https://gist.github.com/1983695

No comments:

Post a Comment