7

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.

asked May 25, 2012 at 2:49

1 Answer 1

6

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]
answered May 25, 2012 at 2:52
Sign up to request clarification or add additional context in comments.

4 Comments

I tried but did not seem to get it working. E.g. compile(a.body[0],'','eval') gave the error expected Expression node, got Expr. (Is Expr not just short for Expression?)
No - Expr is what is contained in the body of an Expression. Try just passing a instead of a.body[0]. (From the grammar.)
Try using ast.parse(src, mode='eval') to get an Expression object.
about your edit: if I change the mode to 'eval' I get problems other-where in my code

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.