修改Python AST时保留注释

4

我目前正在使用Python中的AST。我输入一个Python文件,生成它的AST,进行修改,然后重新编译回源代码。我正在使用一个转换器将getter添加到类中(我正在使用ast.NodeTransformer的访问者模式)。目前我的代码按预期工作,但不保留注释,这是我的问题。以下是我的代码:

#visits nodes and generates getters or setters
def genGet(file,type,func):
    global things
    things['func'] = func
    things['type'] = type
    with open(file) as f:
        code = f.read()             #get the code
    tree = ast.parse(code)          #make the AST from the code
    genTransformer().visit(tree)    #lets generate getters or setters depending on type argument given in our transformer so the genTransformer function
    source = meta.asttools.dump_python_source(tree) #recompile the modified ast to source code
    newfile = "{}{}".format(file[:-3],"_mod.py")
    print "attempting to write source code new file: {}".format(newfile) #tell everyone we will write our new source code to a file
    outputfile = open(newfile,'w+')
    outputfile.write(source)        #write our new source code to a file
    outputfile.close()


class genTransformer(ast.NodeTransformer):
    ...

我已经对lib2to3进行了一些研究,它显然可以保留注释,但目前还没有找到任何有助于解决我的问题的东西。例如,我找到了下面的代码,但并不真正理解它。它似乎可以保留注释,但不允许我进行修改。当运行时,我会收到缺少属性错误。

import lib2to3
from lib2to3.pgen2 import driver
from lib2to3 import pygram, pytree
import ast

def main():
    filename = "%s" % ("exfunctions.py")
    with open(filename) as f:
        code = f.read()
    drv = driver.Driver(pygram.python_grammar, pytree.convert)
    tree = drv.parse_string(code, True)
    # ast transfomer breaks if it is placed here
    print str(tree)
    return

我在寻找一个能够保留注释的AST转换包或策略时遇到了困难。目前为止,我的研究并没有帮助我解决问题。请问有什么方法可以让我修改AST同时又保留注释?


2
注释不是AST的一部分,就像它们不是Python源代码生成的字节码的一部分一样。与空白行一样,在创建AST节点时会被丢弃。 - Martijn Pieters
2
2to3库使用自己的标记器和解析器;lib2to3.pgen2.tokenize源代码包含注释:它旨在完全匹配Python标记器的工作方式,除了它为注释生成COMMENT标记并为所有运算符提供OP类型 - Martijn Pieters
2
@IraBaxter:不,它的自定义解析器会保留它们。 - Martijn Pieters
1
lib2to3解析器生成的解析树与AST模块不兼容;我猜你得看看能否将fixers支持转化为可重用的内容。 - Martijn Pieters
2
@IraBaxter:AST使用普通的Python解析器。lib2to3解析器生成自己的树(不兼容ast模块)。它保留注释;在lib2to3.pytree中的注释说明:这是一个非常具体的解析树;我们需要保留每个标记,甚至是标记之间的注释和空格。 - Martijn Pieters
显示剩余3条评论
1个回答

3

LibCST是一个Python具体语法树解析器和工具包,可用于解决您的问题。

它提供了类似ast的语法树,但保留了格式化信息。

它还提供了用于树修改的转换器模式。

https://github.com/Instagram/LibCST/

https://libcst.readthedocs.io/en/latest/index.html

import libcst as cst

class NameTransformer(cst.CSTTransformer):
    def leave_Name(self, original_node, updated_node):
        return cst.Name(updated_node.value.upper())

使用这样的NameTransformer,我们可以将源代码中的所有名称转换为大写:

>>> m = cst.parse_module("def fn(): return (value)")
>>> m.visit(NameTransformer()).code

'def FN(): return VALUE'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接