has_method

Peter Otten __peter__ at web.de
Tue Aug 31 09:33:13 EDT 2004


Gandalf wrote:

> But since I have my method name in a variable, it will be this way:
> 
> methods = dir(self)
> if methodname in methods:
>     cmd = "self." + methodname
>     method = eval(cmd)
> 
> This is what I wanted to avoid - i.e. the use of eval. There must be an
> easier and quicker way to do this.

method = getattr(self, methodname, None)
if method:
    method(arg1, arg2)

Note that this may still fail if the attribute's value is not callable (and
bool(method) True). 
Use 

try:
    method(arg1, arg2)
except TypeError:
    pass

to guard against that.

Peter




More information about the Python-list mailing list