如何正确地解析python函数docstring?

2024-04-29 06:43:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的docstring解析器示例,用于打印函数的代码字符串:

import ast
import astunparse

class AnalysisNodeVisitor(ast.NodeVisitor):
    def __init__(self, nodename):
        super().__init__()
        self.nodename=nodename
        self.setVariables={}
    def visit_FunctionDef(self,node):
        for thing in node.body:
            if isinstance(thing, ast.Expr):
                print(astunparse.unparse(thing))
        

        
Analyzer=AnalysisNodeVisitor("example1")
tree=ast.parse('''\
def add(a,b):  
    """
    this adds two numbers
    """
    return a+b
''')
Analyzer.visit(tree)

对于本例,输出如下:

enter image description here

'\n    this adds two numbers\n    '

这就是我不明白的,有没有一种方法可以按原样打印(或者更确切地说是解析然后解压)文档字符串:

"""
    this adds two numbers
"""

这只是一个展示我的问题的示例,在我的真实示例中,我尝试转换一个python文件(使用ast模块中的NodeRasNformer类)并从中编写一个副本,在以这种方式转换某些转换信息和所有文档字符串之后,我还使用了astunparse.unparse方法,就像在本示例中一样


Tags: 字符串importself示例initdefthisast