source: vendor/python/2.5/Demo/parser/example.py@ 3225

Last change on this file since 3225 was 3225, checked in by bird, 19 years ago

Python 2.5

File size: 5.6 KB
Line 
1"""Simple code to extract class & function docstrings from a module.
2
3This code is used as an example in the library reference manual in the
4section on using the parser module. Refer to the manual for a thorough
5discussion of the operation of this code.
6"""
7
8import os
9import parser
10import symbol
11import token
12import types
13
14from types import ListType, TupleType
15
16
17def get_docs(fileName):
18 """Retrieve information from the parse tree of a source file.
19
20 fileName
21 Name of the file to read Python source code from.
22 """
23 source = open(fileName).read()
24 basename = os.path.basename(os.path.splitext(fileName)[0])
25 ast = parser.suite(source)
26 return ModuleInfo(ast.totuple(), basename)
27
28
29class SuiteInfoBase:
30 _docstring = ''
31 _name = ''
32
33 def __init__(self, tree = None):
34 self._class_info = {}
35 self._function_info = {}
36 if tree:
37 self._extract_info(tree)
38
39 def _extract_info(self, tree):
40 # extract docstring
41 if len(tree) == 2:
42 found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1])
43 else:
44 found, vars = match(DOCSTRING_STMT_PATTERN, tree[3])
45 if found:
46 self._docstring = eval(vars['docstring'])
47 # discover inner definitions
48 for node in tree[1:]:
49 found, vars = match(COMPOUND_STMT_PATTERN, node)