function to return a list of all methods for an object

Kevin Altis altis at semi-retired.com
Fri Mar 5 21:17:50 CET 2004


"F. Petitjean" <littlejohn.75 at news.noos.fr> wrote in message
news:4048d717$0$277$626a14ce at news.free.fr...
> On Fri, 5 Mar 2004 10:39:23 -0800, Kevin Altis <altis at semi-retired.com>
wrote:
> > I need a way of getting a list of all the methods for an object. I want
the
> > unbound methods for the objects class for some further manipulation.
>
> > ... I came up with
> > a much simpler version that uses dir(), but would like a sanity check
before
> > committing to it. Perhaps there is a better way? This only needs to work
> > with Python 2.2 and later, so I won't mind say "Doh!" if I've missed the
> > obvious simple solution and someone points out my stupidity.
> >
> >
> > import types
> > import pprint
> import inspect
> help(inspect.getmembers)
>
> >
> > def getMethods(object):
> #  don't use object !
> >     methods = []
> >     names = dir(object.__class__)
> >     for name in names:
> >         m = getattr(object.__class__, name)
> >         if isinstance(m, types.MethodType):
> >             #print "method:", m
> >             methods.append(m)
> >     return methods
> >
> >
> Try it :
> b = inspect.BlockFinder()
> inspect.getmembers(inspect.BlockFinder, inspect.ismethod)

Awesome! Looks like I need to do a little refactoring if I'm going to deal
with the list of tuples result, but in the meantime I can do a list
comprehension like this in in the test so I still have a list of unbound
methods.

methods = [t[1] for t in inspect.getmembers(e.__class__, inspect.ismethod)]

Thanks for pointing out inspect,

ka





More information about the Python-list mailing list