blob: 4994bf9100f032b04c34890bcbb5db259ba22bf6 [file] [log] [blame]
Guido van Rossumeee94981991-11-12 15:38:08 +00001# New dir() function and other attribute-related goodies
2
3# This should become a built-in function
4#
5def getattr(x, name):
6 return eval('x.'+name)
7
8# This should be the new dir(), except that it should still list
9# the current local name space by default
10#
11def listattrs(x):
12 try:
13 dictkeys = x.__dict__.keys()
Guido van Rossum946749f1991-12-26 13:04:02 +000014 except (AttributeError, TypeError):
Guido van Rossumeee94981991-11-12 15:38:08 +000015 dictkeys = []
16 #
17 try:
18 methods = x.__methods__
Guido van Rossum946749f1991-12-26 13:04:02 +000019 except (AttributeError, TypeError):
Guido van Rossumeee94981991-11-12 15:38:08 +000020 methods = []
21 #
22 try:
23 members = x.__members__
Guido van Rossum946749f1991-12-26 13:04:02 +000024 except (AttributeError, TypeError):
Guido van Rossumeee94981991-11-12 15:38:08 +000025 members = []
26 #
27 try:
28 the_class = x.__class__
Guido van Rossum946749f1991-12-26 13:04:02 +000029 except (AttributeError, TypeError):
Guido van Rossumeee94981991-11-12 15:38:08 +000030 the_class = None
31 #
32 try:
33 bases = x.__bases__
Guido van Rossum946749f1991-12-26 13:04:02 +000034 except (AttributeError, TypeError):
Guido van Rossumeee94981991-11-12 15:38:08 +000035 bases = ()
36 #
37 total = dictkeys + methods + members
38 if the_class:
39 # It's a class instace; add the class's attributes
40 # that are functions (methods)...
41 class_attrs = listattrs(the_class)
42 class_methods = []
43 for name in class_attrs:
44 if is_function(getattr(the_class, name)):
45 class_methods.append(name)
46 total = total + class_methods
47 elif bases:
48 # It's a derived class; add the base class attributes
49 for base in bases:
50 base_attrs = listattrs(base)
51 total = total + base_attrs
52 total.sort()
53 return total
54 i = 0
55 while i+1 < len(total):
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000056 if total[i] == total[i+1]:
Guido van Rossumeee94981991-11-12 15:38:08 +000057 del total[i+1]
58 else:
59 i = i+1
60 return total
61
62# Helper to recognize functions
63#
64def is_function(x):
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000065 return type(x) == type(is_function)
Guido van Rossumeee94981991-11-12 15:38:08 +000066
67# Approximation of builtin dir(); this lists the user's
68# variables by default, not the current local name space.
69# Use a class method to make a function that can be called
70# with or without arguments.
71#
Guido van Rossum946749f1991-12-26 13:04:02 +000072class _dirclass:
Guido van Rossumeee94981991-11-12 15:38:08 +000073 def dir(args):
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000074 if type(args) == type(()):
Guido van Rossumeee94981991-11-12 15:38:08 +000075 return listattrs(args[1])
76 else:
77 import __main__
78 return listattrs(__main__)
79dir = _dirclass().dir