Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 1 | # New dir() function and other attribute-related goodies |
| 2 | |
| 3 | # This should become a built-in function |
| 4 | # |
| 5 | def 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 | # |
| 11 | def listattrs(x): |
| 12 | try: |
| 13 | dictkeys = x.__dict__.keys() |
| 14 | except (NameError, TypeError): |
| 15 | dictkeys = [] |
| 16 | # |
| 17 | try: |
| 18 | methods = x.__methods__ |
| 19 | except (NameError, TypeError): |
| 20 | methods = [] |
| 21 | # |
| 22 | try: |
| 23 | members = x.__members__ |
| 24 | except (NameError, TypeError): |
| 25 | members = [] |
| 26 | # |
| 27 | try: |
| 28 | the_class = x.__class__ |
| 29 | except (NameError, TypeError): |
| 30 | the_class = None |
| 31 | # |
| 32 | try: |
| 33 | bases = x.__bases__ |
| 34 | except (NameError, TypeError): |
| 35 | 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): |
| 56 | if total[i] = total[i+1]: |
| 57 | del total[i+1] |
| 58 | else: |
| 59 | i = i+1 |
| 60 | return total |
| 61 | |
| 62 | # Helper to recognize functions |
| 63 | # |
| 64 | def is_function(x): |
| 65 | return type(x) = type(is_function) |
| 66 | |
| 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 | # |
| 72 | class _dirclass(): |
| 73 | def dir(args): |
| 74 | if type(args) = type(()): |
| 75 | return listattrs(args[1]) |
| 76 | else: |
| 77 | import __main__ |
| 78 | return listattrs(__main__) |
| 79 | dir = _dirclass().dir |