Convert ast node into python object

孤人 提交于 2019-12-10 15:45:29

问题


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.


回答1:


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]


来源:https://stackoverflow.com/questions/10747873/convert-ast-node-into-python-object

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