Finding the public callables of self

Russell Warren russandheather at gmail.com
Thu Feb 9 12:35:14 EST 2006


> import inspect
> myCallables = [name for name, value in inspect.getmembers(self) if not
> name.startswith('_') and callable(value)]

Thanks.  I forgot about the inspect module.  Interestingly, you've also
answered my question more than I suspect you know!  Check out the code
for inspect.getmembers():

def getmembers(object, predicate=None):
    """Return all members of an object as (name, value) pairs sorted by
name.
    Optionally, only return members that satisfy a given predicate."""
    results = []
    for key in dir(object):
        value = getattr(object, key)
        if not predicate or predicate(value):
            results.append((key, value))
    results.sort()
    return results

Seems familiar!  The fact that this is using dir(), getattr(), and
callable() seems to tell me there is no better way to do it.  I guess
my method wasn't as indirect as I thought!

And thanks for the reminder about getattr() instead of
__getattribute__() and other streamlining tips.

Russ




More information about the Python-list mailing list