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

Peter Otten __peter__ at
Tue Sep 30 21:49:00 CEST 2003

Robert Brewer wrote:

> 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?

Well, *all* Exceptions are only for the programmer, as in an ideal world a
user would never see a traceback. The Exception subclass is intended to
give the programmer the possibility to handle different problems in
different places. 
A typical use case for get_func() would be in a plug-in infrastructure and
thus must be dealt with in the production environment.
As an AssertionError is normally raised by the assert statement which will
be removed when the code is compiled with the -O optimize flag, your usage
is definitely non-standard.


More information about the Python-list mailing list