Using the imp module

Fredrik Lundh fredrik at pythonware.com
Tue Oct 10 10:33:52 EDT 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")
    try:
        module = __import__("module")
    finally:
        sys.path[:] = path # restore

or, often as useful,

    namespace = {}
    execfile("directory/module.py", 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:

    globals().update(namespace)

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]

</F> 






More information about the Python-list mailing list