将 ast 节点转换为 python 对象 [英] Convert ast node into python object
本文介绍了将 ast 节点转换为 python 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个 ast
节点,它可以自己计算,但对于 ast.literal_eval
来说不够文字,例如列表理解
src = '[i**2 for i in range(10)]'a = ast.parse(src)
现在 a.body[0]
是一个 ast.Expr
而 a.body[0].value
是一个 ast.ListComp
.我想获得 eval(src)
将产生的列表,但只给出了 ast.Expr
节点.
解决方案
也许您正在寻找 compile()
?对 AST 对象调用 compile()
的结果是一个可以传递给 eval()
的代码对象.
Given an ast
node that can be evaluated by itself, but is not literal enough for ast.literal_eval
e.g. a list comprehension
src = '[i**2 for i in range(10)]'
a = ast.parse(src)
Now a.body[0]
is an ast.Expr
and a.body[0].value
an ast.ListComp
. I would like to obtain the list that eval(src)
would result, but given only the ast.Expr
node.
解决方案
Perhaps you're looking for compile()
? The result of calling compile()
on an AST object is a code object that can be passed to eval()
.
>>> src = '[i**2 for i in range(10)]'
>>> b = ast.parse(src, mode='eval')
>>> eval(compile(b, '', 'eval'))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
这篇关于将 ast 节点转换为 python 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文