howto get function from module, known by string names?

Carsten Haese carsten at uniqsys.com
Mon May 21 10:55:44 EDT 2007


On Mon, 2007-05-21 at 06:13 -0700, dmitrey wrote:
> And howto check does module 'asdf' exist (is available for import) or
> no? (without try/cache of course)

Why would you need to do that? What are you planning to do when you have
determined that the module doesn't exist? Surely you're not planning on
swallowing the error silently, because that would make your program very
hard to debug. The Pythonic response is to raise an exception, but then
you might as well just propagate the exception that __import__ already
raises:

>>> def myfunc(module_string1, func_string2, *args):
...   func = getattr(__import__(module_string1), func_string2)
...   return func(*args)
... 
>>> myfunc("asdf", "spam")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in myfunc
ImportError: No module named asdf

Hope this helps,

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list