has_method (solution found)
Alex Martelli
aleaxit at yahoo.com
Wed Sep 1 03:32:30 EDT 2004
Gandalf <gandalf at geochemsource.com> wrote:
> Somebody sent me a private e-mail.
> It must be common for such silly questions that would just spam the
> list. :-)
> I'll write down the final solution anyway.
>
>
> def getmethod(name):
> methodList = [e for e in dir(self) if callable(getattr(self, e))]
> if name in methodList:
> return getattr(self,name)
> else:
> return None
I don't think this solution is 'final' -- I don't particularly like it,
in fact. This function claims to return a method (or None) but can in
fact return any callable whatsoever, whether it be a method or not;
either the name and specification are bogus, or the code is. And this
function uses a global 'self' name, which is really terrible...!
Standard library module inspect enables a superior solution:
import inspect
def getmethod(obj, name):
result = getattr(obj, name, None)
if inspect.ismethod(result):
return result
else:
return None
There are other ways to check whether result is a method, of course, but
the best way to program something is to NOT have to program it... just
reuse a good, solid solution that somebody else already programmed,
documented, tested, and placed in the standard library, all ready for
you!
Alex
More information about the Python-list
mailing list