Skip to content

Checking docstrings with an ast.NodeVisitor #350

@BalzaniEdoardo

Description

@BalzaniEdoardo

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions