| 1 | """Simple code to extract class & function docstrings from a module.
|
|---|
| 2 |
|
|---|
| 3 | This code is used as an example in the library reference manual in the
|
|---|
| 4 | section on using the parser module. Refer to the manual for a thorough
|
|---|
| 5 | discussion of the operation of this code.
|
|---|
| 6 | """
|
|---|
| 7 |
|
|---|
| 8 | import os
|
|---|
| 9 | import parser
|
|---|
| 10 | import symbol
|
|---|
| 11 | import token
|
|---|
| 12 | import types
|
|---|
| 13 |
|
|---|
| 14 | from types import ListType, TupleType
|
|---|
| 15 |
|
|---|
| 16 |
|
|---|
| 17 | def 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 |
|
|---|
| 29 | class 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)
|
|---|
|
|---|