将ast节点转换为python对象

将ast节点转换为python对象

本文介绍了将ast节点转换为python对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

给出一个 ast 节点,该节点可以自己评估,但对于 ast.literal_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)

现在 a.body [0] ast.Expr a.body [0] .value ast.ListComp 。我想获取将生成 eval(src)的列表,但仅给出 ast.Expr 节点。

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.

推荐答案

也许您正在寻找?在AST对象上调用 compile()的结果是一个代码对象,可以将其传递给 eval()

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对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:03