-
Notifications
You must be signed in to change notification settings - Fork 13
Open
Description
Currently, in order to check all docstrings a AST tree is traversed fully and for each node we are trying to extract the docstrings. This may result in a lot of unnecessary node visits that can be avoided using an ast.NodeVisitor
targeting specific nodes. With a visitor one can target nodes which have docstrings:
import ast
class DocstringVisitor(ast.NodeVisitor):
def __init__(self, path):
# store what is not passing checks
self.path = path
self.links = []
self.backticks = []
def check_docstring(self, node, name):
doc = ast.get_docstring(node)
# check logic
def visit_FunctionDef(self, node):
self.check_docstring(node, node.name)
self.generic_visit(node) # remove this line if only top-level docstrings needed
def visit_AsyncFunctionDef(self, node):
self.check_docstring(node, node.name)
self.generic_visit(node) # remove this line if only top-level docstrings needed
def visit_ClassDef(self, node):
self.check_docstring(node, node.name)
self.generic_visit(node) # keep, so that methods are also processed
if __name__ == "__main__":
with open(path) as f:
tree = ast.parse(f.read(), filename=str(path))
visitor = DocstringVisitor(path)
visitor.visit(tree)
print(visitor.links)
print(visitor.backticks)
Metadata
Metadata
Assignees
Labels
No labels