How to instatiate a class of which the name is only known at runtime?

Robert Brewer fumanchu at amor.org
Tue Sep 30 12:54:16 EDT 2003


> note that module names are stored fully qualified in sys.modules so
the try
> clause in your will always fail with modules like os.path....
> __import__() does a lookup in sys.modules so that you need not recode
it.

Thanks! I think that try: block was left over from an older version
which used imp.find_module and .load_module. Now that I'm not splitting
out the module name, I also don't need to have two __import__ calls.
Finally, I sped up the initial parsing with rfind() and slicing.

def get_func(fullFuncName):
    """Dynamically load a module and retrieve reference to the function
(NOT an instance)."""
    
    # Parse out the path, module, and function
    lastDot = fullFuncName.rfind(".")
    funcName = fullFuncName[lastDot + 1:]
    modPath = fullFuncName[:lastDot]
    
    aMod = __import__(modPath, globals(), locals(), [''])
    aFunc = getattr(aMod, funcName)
    
    # Assert that the function is a *callable* attribute.
    if not callable(aFunc): raise AssertionError("%s is not callable." %
fullFuncName)
    
    # Return a reference to the function itself, not the results of the
function.
    return aFunc

> Maybe you should raise a TypeError rather than an ImportError to
indicate
> that what is expected to be a function is not callable.

How about an AssertionError, since it's only included for programmers,
not users?


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org





More information about the Python-list mailing list