Using the imp module

Fredrik Lundh fredrik at
Tue Oct 10 16:33:52 CEST 2006

Claus Tondering wrote:

> Thank you, I can use that in some cases. However, I need to import a
> file that is not in the load path.

that's pretty straightforward:

    path = list(sys.path)
    sys.path.insert(0, "directory")
        module = __import__("module")
        sys.path[:] = path # restore

or, often as useful,

    namespace = {}
    execfile("directory/", namespace)

the latter executes the external code everything you run it (unlike import,
which uses the sys.modules cache), and puts everything defined by the
external script into the given dictionary.

to import all that into your own module, you can do:


for extra bonus, you may want to check the __all__ attribute, and if that's
not present, filter out anything that starts with an underscore:

    all_names = namespace.get("__all__")
    if all_names is None:
        all_names = (key for key in namespace where key[0] != "_")
    my_namespace = globals()
    for name in all_names:
        my_namespace[name] = namespace[name]


More information about the Python-list mailing list