cpython/Lib/newdir.py

74 lines
1.5 KiB
Python
Raw Normal View History

# New dir() function
1991-11-12 11:38:08 -04:00
# This should be the new dir(), except that it should still list
# the current local name space by default
1991-11-12 11:38:08 -04:00
def listattrs(x):
try:
dictkeys = x.__dict__.keys()
1991-12-26 09:04:02 -04:00
except (AttributeError, TypeError):
1991-11-12 11:38:08 -04:00
dictkeys = []
#
try:
methods = x.__methods__
1991-12-26 09:04:02 -04:00
except (AttributeError, TypeError):
1991-11-12 11:38:08 -04:00
methods = []
#
try:
members = x.__members__
1991-12-26 09:04:02 -04:00
except (AttributeError, TypeError):
1991-11-12 11:38:08 -04:00
members = []
#
try:
the_class = x.__class__
1991-12-26 09:04:02 -04:00
except (AttributeError, TypeError):
1991-11-12 11:38:08 -04:00
the_class = None
#
try:
bases = x.__bases__
1991-12-26 09:04:02 -04:00
except (AttributeError, TypeError):
1991-11-12 11:38:08 -04:00
bases = ()
#
total = dictkeys + methods + members
if the_class:
# It's a class instace; add the class's attributes
# that are functions (methods)...
class_attrs = listattrs(the_class)
class_methods = []
for name in class_attrs:
if is_function(getattr(the_class, name)):
class_methods.append(name)
total = total + class_methods
elif bases:
# It's a derived class; add the base class attributes
for base in bases:
base_attrs = listattrs(base)
total = total + base_attrs
total.sort()
return total
i = 0
while i+1 < len(total):
1992-01-01 15:35:13 -04:00
if total[i] == total[i+1]:
1991-11-12 11:38:08 -04:00
del total[i+1]
else:
i = i+1
return total
1991-11-12 11:38:08 -04:00
# Helper to recognize functions
1991-11-12 11:38:08 -04:00
def is_function(x):
1992-01-01 15:35:13 -04:00
return type(x) == type(is_function)
1991-11-12 11:38:08 -04:00
# Approximation of builtin dir(); but note that this lists the user's
1991-11-12 11:38:08 -04:00
# variables by default, not the current local name space.
def dir(x = None):
if x is not None:
return listattrs(x)
else:
import __main__
return listattrs(__main__)