is there any way to revert back the AST tree from the dump file of the tree?

≯℡__Kan透↙ 提交于 2020-12-13 07:46:11

问题


c is a parsed tree of a python code:

c=ast.parse(''' for x in y: print(x) ''')

d is the dump file of tree-c

d=ast.dump(c)

the content of d is the following string:

Module(
    body=[For(target=Name(id='x', ctx=Store()), iter=Name(id='y', ctx=Load()),
    body=[Expr(value=Call(func=Name(id='print', ctx=Load()), 
    args=[Name(id='x', ctx=Load())], keywords=[]))], orelse=[])])

I've looked around the net to see if I could find a method to use the content of d, to revert back to the tree c.

Any suggestions?

Thank you


回答1:


You can use eval to get the ast object from the string:

ast_obj = eval(d)

Then, there exist various third party libraries that can convert back to source (Given an AST, is there a working library for getting the source?, Python ast (Abstract Syntax Trees): get back source string of subnode)



来源:https://stackoverflow.com/questions/51366393/is-there-any-way-to-revert-back-the-ast-tree-from-the-dump-file-of-the-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!