]> git.saurik.com Git - wxWidgets.git/blob - wxPython/wxPython/lib/PyCrust/introspect.py
4139ec66c892465c8833a6840479751e2391abad
[wxWidgets.git] / wxPython / wxPython / lib / PyCrust / introspect.py
1 """Provides a variety of introspective-type support functions for things
2 like call tips and command auto completion."""
3
4 __author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
5 __cvsid__ = "$Id$"
6 __version__ = "$Revision$"[11:-2]
7
8 import inspect
9 import string
10
11 def getAutoCompleteList(command='', locals=None, includeMagic=1, \
12 includeSingle=1, includeDouble=1):
13 """Return list of auto-completion options for command.
14
15 The list of options will be based on the locals namespace."""
16
17 # Get the proper chunk of code from the command.
18 root = getRoot(command, terminator='.')
19 try:
20 object = eval(root, locals)
21 attributes = getAttributeNames(object, includeMagic, \
22 includeSingle, includeDouble)
23 return attributes
24 except:
25 return []
26
27 def getAttributeNames(object, includeMagic=1, includeSingle=1, includeDouble=1):
28 """Return list of unique attributes, including inherited, for an object."""
29 attributes = []
30 dict = {}
31 if includeMagic:
32 try: attributes += object._getAttributeNames()
33 except: pass
34 # Get all attribute names, removing duplicates from the attribute list.
35 for item in getAllAttributeNames(object):
36 dict[item] = None
37 attributes += dict.keys()
38 attributes.sort(lambda x, y: cmp(x.lower(), y.lower()))
39 if not includeSingle:
40 attributes = filter(lambda item: item[0]!='_' or item[1]=='_', attributes)
41 if not includeDouble:
42 attributes = filter(lambda item: item[:2]!='__', attributes)
43 return attributes
44
45 def getAllAttributeNames(object):
46 """Return list of all attributes, including inherited, for an object.
47
48 Recursively walk through a class and all base classes.
49 """
50 attributes = []
51 # Wake up sleepy objects - a hack for ZODB objects in "ghost" state.
52 wakeupcall = dir(object)
53 del wakeupcall
54 # Get attributes available through the normal convention.
55 attributes += dir(object)
56 # For a class instance, get the attributes for the class.
57 if hasattr(object, '__class__'):
58 # Break a circular reference. This happens with extension classes.
59 if object.__class__ is object:
60 pass
61 else:
62 attributes += getAllAttributeNames(object.__class__)
63 # Also get attributes from any and all parent classes.
64 if hasattr(object, '__bases__'):
65 for base in object.__bases__:
66 attributes += getAllAttributeNames(base)
67 return attributes
68
69 def getCallTip(command='', locals=None):
70 """Return call tip text for a command.
71
72 The call tip information will be based on the locals namespace."""
73
74 # Get the proper chunk of code from the command.
75 root = getRoot(command, terminator='(')
76 try:
77 object = eval(root, locals)
78 except:
79 return ''
80 dropSelf = 0
81 if hasattr(object, '__name__'): # Make sure this is a useable object.
82 # Switch to the object that has the information we need.
83 if inspect.ismethod(object) or hasattr(object, 'im_func'):
84 # Get the function from the object otherwise inspect.getargspec()
85 # complains that the object isn't a Python function.
86 object = object.im_func
87 dropSelf = 1
88 elif inspect.isclass(object):
89 # Get the __init__ method function for the class.
90 try:
91 object = object.__init__.im_func
92 dropSelf = 1
93 except AttributeError:
94 for base in object.__bases__:
95 constructor = _find_constructor(base)
96 if constructor is not None:
97 object = constructor
98 dropSelf = 1
99 break
100 name = object.__name__
101 tip1 = ''
102 if inspect.isbuiltin(object):
103 # Builtin functions don't have an argspec that we can get.
104 pass
105 elif inspect.isfunction(object):
106 # tip1 is a string like: "getCallTip(command='', locals=None)"
107 argspec = apply(inspect.formatargspec, inspect.getargspec(object))
108 if dropSelf:
109 # The first parameter to a method is a reference to the
110 # instance, usually coded as "self", and is passed
111 # automatically by Python and therefore we want to drop it.
112 temp = argspec.split(',')
113 if len(temp) == 1: # No other arguments.
114 argspec = '()'
115 else: # Drop the first argument.
116 argspec = '(' + ','.join(temp[1:]).lstrip()
117 tip1 = name + argspec
118 doc = inspect.getdoc(object)
119 if doc:
120 # tip2 is the first separated line of the docstring, like:
121 # "Return call tip text for a command."
122 # tip3 is the rest of the docstring, like:
123 # "The call tip information will be based on ... <snip>
124 docpieces = doc.split('\n\n')
125 tip2 = docpieces[0]
126 tip3 = '\n\n'.join(docpieces[1:])
127 tip = '%s\n\n%s\n\n%s' % (tip1, tip2, tip3)
128 else:
129 tip = tip1
130 return tip.strip()
131 else:
132 return ''
133
134 def getRoot(command, terminator=None):
135 """Return the rightmost root portion of an arbitrary Python command.
136
137 The command would normally terminate with a "(" or ".". Anything after
138 the terminator will be dropped, allowing you to get back to the root.
139 Return only the root portion that can be eval()'d without side effects.
140 """
141 root = ''
142 validChars = "._" + string.uppercase + string.lowercase + string.digits
143 if terminator:
144 # Drop the final terminator and anything that follows.
145 pieces = command.split(terminator)
146 if len(pieces) > 1:
147 command = terminator.join(pieces[:-1])
148 if len(command) == 0:
149 root = ''
150 elif command in ("''", '""', '""""""', '[]', '()', '{}'):
151 # Let empty type delimiter pairs go through.
152 root = command
153 else:
154 # Go backward through the command until we hit an "invalid" character.
155 i = len(command)
156 while i and command[i-1] in validChars:
157 i -= 1
158 # Detect situations where we are in the middle of a string.
159 # This code catches the simplest case, but needs to catch others.
160 if command[i-1] in ("'", '"'):
161 # We're in the middle of a string so we aren't dealing with an
162 # object and it would be misleading to return anything here.
163 root = ''
164 else:
165 # Grab everything from the "invalid" character to the end.
166 root = command[i:]
167 return root
168
169
170