Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Redirect a Python Import to a Relative Directory


Redirect a Python import by using a dummy Python module that deletes its own reference and replaces it with relative module or package.


Allows more control over a relative directory structure


The directory structure being used:


The initial import is in /root/ From inside /root/foo/, we redirect to /root/foo/foo .

# 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
# can store items in sys.argv if exec('import {0}'.format(module_name)) needed, but prints 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
# target of redirection
def bar():
print 'Works'!
# main executed script
import foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment