howto get function from module, known by string names?

dmitrey openopt at ukr.net
Mon May 21 09:13:02 EDT 2007


And howto check does module 'asdf' exist (is available for import) or
no? (without try/cache of course)
Thx, D.

Carsten Haese wrote:
> On 15 May 2007 04:29:56 -0700, dmitrey wrote
> > hi all,
> > can anyone explain howto get function from module, known by string
> > names?
> > I.e. something like
> >
> > def myfunc(module_string1, func_string2, *args):
> >     eval('from ' + module_string1  + 'import ' + func_string2')
> >     return func_string2(*args)
>
> To find a module by its name in a string, use __import__. To find an object's
> attribute by its name in a string, use getattr.
>
> Together, that becomes something like this:
>
> >>> def myfunc(module_string1, func_string2, *args):
> ...    func = getattr(__import__(module_string1), func_string2)
> ...    return func(*args)
> ...
> >>> myfunc("math", "sin", 0)
> 0.0
> >>> myfunc("operator", "add", 2, 3)
> 5
>
> Hope this helps,
>
> --
> Carsten Haese
> http://informixdb.sourceforge.net




More information about the Python-list mailing list