Getting a *full* list of attrib/methods for a class
Pedro RODRIGUEZ
pedro_rodriguez at club-internet.fr
Wed Dec 11 03:21:32 EST 2002
On Wed, 11 Dec 2002 01:29:27 +0100, Terry Hancock wrote:
> I figured there'd be a built-in or special method to get just this, and
> when I experimented with dir() I thought I had it -- but then I realized
> I was testing it in Python 2.2! Is there something I just don't know
> about, or should I just be writing my own recursive search function to
> do the job?
>
Some time ago I faced the same situation, I wanted to have the 2.2
version of dir. So I picked up the C version of Python 2.2 and rewrote it
in pure Python.
(Notice that this is based on 2.2 version, you may check on the latest
version if there have been changes, but the transcription looked quite
straitforward at that time).
Pedro
# new_dir.py
""" Restranscript of python 2.2 dir() builtin.
"""
import types
import sys
def merge_class_dict(dict, aclass):
classdict = getattr(aclass, "__dict__", None)
if classdict is not None:
dict.update(classdict)
bases = getattr(aclass, "__bases__", None)
if bases is not None:
for base in bases:
merge_class_dict(dict, base)
def merge_list_attr(dict, obj, attrname):
list = getattr(obj, attrname, None)
if list is not None:
for item in list:
if type(item) is types.StringType:
dict[item] = None
def new_dir(obj=None):
objType = type(obj)
if obj is None:
result = locals().keys()
elif objType is types.ModuleType:
result = obj.__dict__.keys()
elif objType is types.ClassType or objType is types.TypeType:
dict = {}
merge_class_dict(dict, obj)
result = dict.keys()
else:
dict = getattr(obj, "__dict__", None)
if dict is None:
dict = {}
elif type(dict) is not types.DictType:
dict = {}
else:
dict = dict.copy()
merge_list_attr(dict, obj, "__members__")
merge_list_attr(dict, obj, "__methods__")
itsclass = getattr(obj, "__class__", None)
if itsclass is not None:
merge_class_dict(dict, itsclass)
result = dict.keys()
return result
try:
major, minor, micro, releaselevel, serial = sys.version_info
if (major, minor) >= (2, 2):
new_dir = dir
except:
pass
More information about the Python-list
mailing list