6
import ast
code = '1+1'
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 <module>
 compile(ast.Expression(expr), '<string>', "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
wjandrea
34k10 gold badges69 silver badges107 bronze badges
asked Oct 15, 2018 at 15:24

2 Answers 2

4

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

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

import ast
code = 'a+1'
expr = ast.parse(code).body[0]
print(eval(compile(ast.Expression(expr.value), '<string>', "eval"), {"a": 4}, {}))
wjandrea
34k10 gold badges69 silver badges107 bronze badges
answered Oct 15, 2018 at 15:49
Sign up to request clarification or add additional context in comments.

Comments

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>
answered Oct 15, 2018 at 15:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.