Create a gist now

Instantly share code, notes, and snippets.

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

Summary

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

Purpose

Allows more control over a relative directory structure

Example

The directory structure being used:

root/
    test.py
    foo/
        __init__.py
        foo/
            __init__.py

The initial import is in /root/test.py. From inside /root/foo/_init_.py, 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
foo.bar()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment