Scan a module for top-level functions and classes. Skips objects with an @undoc decorator, or a name starting with '_'.
| 33 | setattr(self, k, v) |
| 34 | |
| 35 | class FuncClsScanner(ast.NodeVisitor): |
| 36 | """Scan a module for top-level functions and classes. |
| 37 | |
| 38 | Skips objects with an @undoc decorator, or a name starting with '_'. |
| 39 | """ |
| 40 | def __init__(self): |
| 41 | ast.NodeVisitor.__init__(self) |
| 42 | self.classes = [] |
| 43 | self.classes_seen = set() |
| 44 | self.functions = [] |
| 45 | |
| 46 | @staticmethod |
| 47 | def has_undoc_decorator(node): |
| 48 | return any(isinstance(d, ast.Name) and d.id == 'undoc' \ |
| 49 | for d in node.decorator_list) |
| 50 | |
| 51 | def visit_If(self, node): |
| 52 | if isinstance(node.test, ast.Compare) \ |
| 53 | and isinstance(node.test.left, ast.Name) \ |
| 54 | and node.test.left.id == '__name__': |
| 55 | return # Ignore classes defined in "if __name__ == '__main__':" |
| 56 | |
| 57 | self.generic_visit(node) |
| 58 | |
| 59 | def visit_FunctionDef(self, node): |
| 60 | if not (node.name.startswith('_') or self.has_undoc_decorator(node)) \ |
| 61 | and node.name not in self.functions: |
| 62 | self.functions.append(node.name) |
| 63 | |
| 64 | def visit_ClassDef(self, node): |
| 65 | if not (node.name.startswith('_') or self.has_undoc_decorator(node)) \ |
| 66 | and node.name not in self.classes_seen: |
| 67 | cls = Obj(name=node.name) |
| 68 | cls.has_init = any(isinstance(n, ast.FunctionDef) and \ |
| 69 | n.name=='__init__' for n in node.body) |
| 70 | self.classes.append(cls) |
| 71 | self.classes_seen.add(node.name) |
| 72 | |
| 73 | def scan(self, mod): |
| 74 | self.visit(mod) |
| 75 | return self.functions, self.classes |
| 76 | |
| 77 | # Functions and classes |
| 78 | class ApiDocWriter(object): |