faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 2 people (50%) answered Yes
Recently 0 of 1 people (0%) answered Yes

Entry

Getting all class/instance methods (was: dir and java classes)

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 251, Jeremy Hylton


"""
Packages: oop
"""
"""
[Shanghaiing this discussion from jpython-interest.]
>>>>> "BAW" == Barry A Warsaw <bwarsaw@cnri.reston.va.us> writes:
  BAW> Okay, so what can you do to get the information you want?
  BAW> Well, it isn't really that difficult to write your own dir()
  BAW> function that, given an instance traversed into the instance's
  BAW> class to find method and attribute names.  For completeness you
  BAW> probably want to cruise the entire class hierarchy (but maybe
  BAW> not).
  BAW> So the issue is, why doesn't dir() do this by default?  You
  BAW> could insert your superdir() into __builtin__, say in your
  BAW> sitecustom.py or $PYTHONSTARTUP file.  Otherwise, that's
  BAW> something to debate in the larger Python community.  If some
  BAW> agreement on exactly what information superdir() would return
  BAW> (and how to make it backward compatible) were reached, I'm sure
  BAW> the changes would find their way into the Python language (and
  BAW> thus JPython).
Maybe we just need to have an introspection module that contains a
bunch of helpers for tasks like these.  By having it in a module, we
don't have to deal with trying to add builtins but we still guarantee
it's part of the standard battery pack.  Once the module exists,
people can use your suggestion and just do something like
    from introspect import *
in one of their own customization files.
What would we need to put in such a module?
I have a getMethods function that gets loaded into my Python
interpreter automatically...
"""
import types
def getMethods(arg):
    methods = {}
    classes = []
    if type(arg) == types.InstanceType:
        classes.append(arg.__class__)
    elif type(arg) == types.ClassType:
        classes.append(arg)
    else:
        raise TypeError, "arg must be class or instance"
    while classes:
        klass = classes[0]
        del classes[0]
        classes = classes + list(klass.__bases__)
        for name in dir(klass):
            attr = getattr(klass, name)
            if callable(attr):
                methods[name] = 1
    return methods.keys()
# added by PSST
if __name__ == "__main__":
    import urllib
    print "dir():"
    print dir(urllib.FancyURLopener)
    print "getMethods():"
    print getMethods(urllib.FancyURLopener)