1 """Parse a Python file and retrieve classes and methods.
3 Parse enough of a Python file to recognize class and method
4 definitions and to find out the superclasses of a class.
6 The interface consists of a single function:
7 readmodule(module, path)
8 module is the name of a Python module, path is an optional list of
9 directories where the module is to be searched. If present, path is
10 prepended to the system search path sys.path.
11 The return value is a dictionary. The keys of the dictionary are
12 the names of the classes defined in the module (including classes
13 that are defined via the from XXX import YYY construct). The values
14 are class instances of the class Class defined here.
16 A class is described by the class Class in this module. Instances
17 of this class have the following instance variables:
18 name -- the name of the class
19 super -- a list of super classes (Class instances)
20 methods -- a dictionary of methods
21 file -- the file in which the class was defined
22 lineno -- the line in the file on which the class statement occurred
23 The dictionary of methods uses the method names as keys and the line
24 numbers on which the method was defined as values.
25 If the name of a super class is not recognized, the corresponding
26 entry in the list of super classes is not a class instance but a
27 string giving the name of the super class. Since import statements
28 are recognized and imported modules are scanned as well, this
29 shouldn't happen often.
32 - Continuation lines are not dealt with at all, except inside strings.
33 - Nested classes and functions can confuse it.
34 - Code that doesn't pass tabnanny or python -t will confuse it, unless
35 you set the module TABWIDTH vrbl (default 8) to the correct tab width
39 - If you have a package and a module inside that or another package
40 with the same name, module caching doesn't work properly since the
41 key is the base name of the module/package.
42 - The only entry that is returned when you readmodule a package is a
43 __path__ whose value is a list which confuses certain class browsers.
45 from package import subpackage
46 class MyClass(subpackage.SuperClass):
48 It can't locate the parent. It probably needs to have the same
49 hairy logic that the import locator already does. (This logic
50 exists coded in Python in the freeze package.)
58 __all__ = [
"readmodule"]
62 _getnext = re.compile(
r"""
76 | " [^"\\\n]* (?: \\. [^"\\\n]*)* "
78 | ' [^'\\\n]* (?: \\. [^'\\\n]*)* '
83 (?P<MethodIndent> [ \t]* )
85 (?P<MethodName> [a-zA-Z_] \w* )
91 (?P<ClassIndent> [ \t]* )
93 (?P<ClassName> [a-zA-Z_] \w* )
95 (?P<ClassSupers> \( [^)\n]* \) )?
101 (?P<ImportList> [^#;\n]+ )
109 [ \t]* \. [ \t]* [a-zA-Z_] \w*
114 (?P<ImportFromList> [^#;\n]+ )
116 """, re.VERBOSE | re.DOTALL | re.MULTILINE).search
122 '''Class to represent a Python class.'''
123 def __init__(self, module, name, super, file, lineno):
133 def _addmethod(self, name, lineno):
137 '''Class to represent a top-level Python function'''
139 Class.__init__(self, module, name,
None, file, lineno)
140 def _addmethod(self, name, lineno):
141 assert 0,
"Function._addmethod() shouldn't be called"
144 '''Backwards compatible interface.
146 Like readmodule_ex() but strips Function objects from the
147 resulting dictionary.'''
151 for key, value
in dict.items():
152 if not isinstance(value, Function):
157 '''Read a module file and return a dictionary of classes.
159 Search for MODULE in PATH and sys.path, read and parse the
160 module and return a dictionary with one entry for each class
161 found in the module.'''
165 i = module.rfind(
'.')
168 package = module[:i].
strip()
169 submodule = module[i+1:].
strip()
174 if _modules.has_key(module):
176 return _modules[module]
177 if module
in sys.builtin_module_names:
179 _modules[module] = dict
186 f, file, (suff, mode, type) = \
187 imp.find_module(module, path)
191 fullpath = list(path) + sys.path
192 f, file, (suff, mode, type) = imp.find_module(module, fullpath)
193 if type == imp.PKG_DIRECTORY:
194 dict[
'__path__'] = [file]
195 _modules[module] = dict
197 f, file, (suff, mode, type) = \
198 imp.find_module(
'__init__', [file])
199 if type != imp.PY_SOURCE:
202 _modules[module] = dict
205 _modules[module] = dict
216 countnl = string.count
217 lineno, last_lineno_pos = 1, 0
225 if m.start(
"Method") >= 0:
227 thisindent = _indent(m.group(
"MethodIndent"))
228 meth_name = m.group(
"MethodName")
231 last_lineno_pos, start)
232 last_lineno_pos = start
234 while classstack
and \
235 classstack[-1][1] >= thisindent:
239 cur_class = classstack[-1][0]
240 cur_class._addmethod(meth_name, lineno)
247 elif m.start(
"String") >= 0:
250 elif m.start(
"Class") >= 0:
252 thisindent = _indent(m.group(
"ClassIndent"))
254 while classstack
and \
255 classstack[-1][1] >= thisindent:
258 countnl(src,
'\n', last_lineno_pos, start)
259 last_lineno_pos = start
260 class_name = m.group(
"ClassName")
261 inherit = m.group(
"ClassSupers")
264 inherit = inherit[1:-1].
strip()
266 for n
in inherit.split(
','):
281 if _modules.has_key(m):
288 cur_class =
Class(module, class_name, inherit,
290 dict[class_name] = cur_class
291 classstack.append((cur_class, thisindent))
293 elif m.start(
"Import") >= 0:
295 for n
in m.group(
"ImportList").
split(
','):
304 elif m.start(
"ImportFrom") >= 0:
306 mod = m.group(
"ImportFromPath")
307 names = m.group(
"ImportFromList").
split(
',')
332 assert 0,
"regexp _getnext found something unexpected"
336 def _indent(ws, _expandtabs=string.expandtabs):
337 return len(_expandtabs(ws, TABWIDTH))