function to return a list of all methods for an object

Peter Otten __peter__ at
Fri Mar 5 20:07:27 CET 2004

Kevin Altis 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.
> My old way of doing this did a recursive iteration over __bases__ and the
> code seems sort of fragile, especially with multiple inheritance. 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.
> # return a list of unbound methods for an object
> def getMethods(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

Seems sensible...

> Here's the output:
> <__main__.E instance at 0x007EABC0> __main__.E
> B dummy
> [<unbound method E.dummy>,
>  <unbound method E.fourD>,
>  <unbound method E.oneA>,
>  <unbound method E.threeC>,
>  <unbound method E.twoB>]

... and works.

You might consider using inspect.getmembers() instead, which is implemented
in a similar fashion:

def getmembers(object, predicate=None):
    results = []
    for key in dir(object):
        value = getattr(object, key)
        if not predicate or predicate(value):
            results.append((key, value))
    return results

Providing the predicate is straightforward, so it all depends on wether you
like the (name, method) tuples instead of your method-only in the resulting


More information about the Python-list mailing list