Skip to content

Instantly share code, notes, and snippets.

@majgis
Created March 6, 2012 05:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save majgis/1983695 to your computer and use it in GitHub Desktop.
Save majgis/1983695 to your computer and use it in GitHub Desktop.
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