Differences between revisions 5 and 6
Revision 5 as of 2009-08-14 18:50:55
Size: 922
Editor: CarlNobile
Comment:
Revision 6 as of 2009-12-14 19:29:39
Size: 962
Editor: CarlNobile
Comment:
Deletions are marked like this. Additions are marked like this.
Line 18: Line 18:
    if len(asList) != len(fromList): raise ValueError('asList != fromList')
if len(asList) != len(fromList):
        msg = 'len(asList) != len(fromList)'
       
raise ValueError(msg)

Dynamically Importing Python Modules

If you ever need to dynamically import Python modules this short function will do the trick. The modules will be imported into the importing module's __main__ scope.

def importMods(path, fromList, asList=None):
    """
    This function will import modules into the global scope relative to
    this function.

    @param path: The path to the module.
    @param fromList: A list containing the items to import.
    @keyword asList: A one for one match to C{fromList} indicating the
                     names to be used in the import.
    """
    modules = __import__(path, globals(), locals(), fromList, -1)
    if not asList: asList = fromList

    if len(asList) != len(fromList):
        msg = 'len(asList) != len(fromList)'
        raise ValueError(msg)

    for asMod, mod in zip(asList, fromList):
        exec "importMods.func_globals['%s'] = modules.%s" % (asMod, mod)

DynamicallyImportingPythonModules (last edited 2009-12-14 19:29:39 by CarlNobile)