[JPython] dir and java classes

Jeremy Hylton jeremy at cnri.reston.va.us
Tue Oct 26 16:57:34 EDT 1999


[Shanghaiing this discussion from jpython-interest.]

>>>>> "BAW" == Barry A Warsaw <bwarsaw at 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()

Jeremy





More information about the Python-list mailing list