How to call a class method from a string representing a class name

Andre Fortin andrefor at axionet.com
Sun Jan 28 22:27:35 EST 2001


Alex Martelli wrote:

> So, a solution might be:
> 
> try:
>     callable = test.myFunc
> except (NameError,AttributeError):
>     pass
> else:
>     callable('Some Text')
> 

Using "test.myFunc" returns a "AttributeError: myFunc", since 
"test" is a string. With your suggestion though, here is 
a way better snippet of code:


import sys
import test

className = 'test'

try:
    sys.modules[className].myFunc('Some text')
except KeyError:
    pass


Very clean. It avoids both the globals() and vars() calls.


> (a KeyError raised inside 'callable' in your case
> is silently caught and hidden -- IS that what you want?)

In my case, yes. In this snippet context, what counts is the existence
of 
the "test" module.

Thank you for your help!

-- 

Andre



More information about the Python-list mailing list