__methods__

Chris Hoffmann (choffman@dvcorp.com)
Thu, 2 Feb 95 10:57:01 EST

I had gotten so used to using "__methods__" on an object to see what
you can do with it I'd forgotten that this isn't really built-in to
the language but is a convention used by built-in types. The, today I
saw this:

Python 1.1 (Jan 25 1995)
Copyright 1991-1994 Stichting Mathematisch Centrum, Amsterdam
>>> class x:
... def y(): pass
... def z(): pass
...
>>> a = x()
>>> a.__methods__
Traceback (innermost last):
File "<stdin>", line 1, in ?
AttributeError: __methods__

Bummer.

So I tried to be clever and do the following:

>>> class x:
... def z():pass
... __methods__ = init_meth(vars())

where

def init_meth(d):
class c:
def y(): pass
l = []
for k in d.keys():
if type(d[k]) is type(c.y): ### only methods
l.append(k)
l.sort()
return l

The problem is that in the dictionary "init_meth" receives, "x.z" is
of type 'function', not of type 'instance method'. I can fix the above
by having it check to see if type(d[k]) is of type 'function', but I'm
curious how and why the type of z changes (after the class is fully
defined, the type of "x.z" is indeed 'instance method').

Then again, I'm not sure this is quite what I want to check against
anyway as an attribute might be a function object but not a method.

It did get me wondering, however, if there is any reason the Python
implementation couldn't be changed to do something similar for
non-builtin classes. That is, if classobject.c'class_getattr()
couldn't check to see if the attribute is named '__members__' and do
the equivalent of init_meth(). Even better, something like init_meth()
that actually worked! Or have there been just too many other more
worthwhile things to do?

Chris

-- 
Chris Hoffmann				DataViews Corporation
choffman@dvcorp.com			47 Pleasant St. Northampton MA 01060
GCS d H s+: g+ ?p a w v+ C+$ US+ P++(++++) L E+(+++) N++ K W--->-- M+
V- po- Y+ t+ 5+(+++) Jx R G tv b+++ D+ B-() e+++ u++ h---- f r+++ n--- y++++