How do you compile an ast.Expt?

谁都会走 提交于 2019-12-11 03:14:56

问题


code='1+1'
import ast
expr = ast.parse(code).body[0]
print(type(expr))
compile(ast.Expression(expr), 'string', "eval")

gets me

class '_ast.Expr'

Traceback (most recent call last): File "test_ast.py", line 6, in compile(ast.Expression(expr), '', "eval") TypeError: expected some sort of expr, but got <_ast.Expr object at> 0x7fe89442d9e8>

compile(expr, '<string>', "eval")

does not works either:

TypeError: expected Expression node, got Expr


回答1:


An interesting explanation about Expressions can be found here.

But basically, the answer's first paragraph says it all:

Expr is not the node for an expression per se but rather an expression-statement --- that is, a statement consisting of only an expression. This is not totally obvious because the abstract grammar uses three different identifiers Expr, Expression, and expr, all meaning slightly different things.

So, in your case, you would need to dump the Expr first:

>>> ast.dump(expr)
'Expr(value=BinOp(left=Num(n=1), op=Add(), right=Num(n=1)))'
>>> compile(ast.dump(expr), 'string', "eval")
<code object <module> at 0x1065d2ae0, file "string", line 1>



回答2:


TLDR : replace expr by ast.Expression(expr.value)

A comment on this Convert ast node into python object and makeMonday answer gave me the solution:

code = 'a+1'
import ast
expr = ast.parse(code).body[0]
print(eval(compile(ast.Expression(expr.value), '<string>', "eval"), {"a": 4}, {}))


来源:https://stackoverflow.com/questions/52819981/how-do-you-compile-an-ast-expt

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