如何在Python中创建多行三引号ast节点字符串?
如何用AST生成多行三引号格式的Python文档字符串?
你当前的代码通过ast.Str生成的文档字符串会被渲染成单行带转义字符的形式,无法直接输出多行三引号格式。这是因为AST的Str节点仅存储字符串内容,不记录引号格式——最终的引号样式由代码生成工具(如Python内置的ast.unparse或第三方库)决定。
要生成你期望的多行三引号格式,可使用能识别多行字符串并自动选择三引号渲染的代码生成库,比如astor。以下是修改后的实现:
import ast import astor class DocstringWriter(ast.NodeTransformer): def visit_FunctionDef(self, node): # 替换为你从GPT获取的实际文档字符串 new_docstring = """ esc(s) Returns a string with all backslashes escaped. Parameters ---------- s : str The string to escape. Returns ------- str The escaped string. Examples -------- >>> esc('\\\\') '\\\\\\\\' """ new_docstring_node = self.make_docstring_node(new_docstring) if ast.get_docstring(node): node.body[0] = new_docstring_node else: node.body.insert(0, new_docstring_node) return node def make_docstring_node(self, docstring): return ast.Expr(value=ast.Str(docstring)) # 示例用法 with open("your_file.py", "r") as f: tree = ast.parse(f.read()) transformer = DocstringWriter() new_tree = transformer.visit(tree) # 用astor生成代码,自动将多行字符串渲染为三引号格式 print(astor.to_source(new_tree))
关键说明:
ast.Str仅保存字符串实际内容,引号格式由代码生成工具处理。astor会检测字符串是否包含换行符,自动选择三引号渲染,生成你想要的格式。- 若使用Python 3.9+内置的
ast.unparse,它也会对含换行的字符串自动使用三引号,只需确保字符串内容的换行和缩进正确。
内容的提问来源于stack exchange,提问作者Clerni
相关产品推荐
相关产品推荐

