3

I have the AST of a python program and want to manually evaluate the condition of an if statement.

cond = node.test
b = eval(compile(cond,"<string>","eval"))
print b

Where node is the If-Node, gives me TypeError: expected Expression node, got Compare, even if Compare is an expression according to the grammar in the python doc of ast.

Any ideas?

1 Answer 1

5

You have a ast.expr subclass, not a ast.Expression top-level node.

compile() can only take a mod object, so one of Module, Interactive or Expression, depending on the third argument to compile(). For 'eval', use ast.Expression().

You can create one containing the ast.Compare node:

expr = ast.Expression(cond)

because the abstract grammar defines it as:

Expression(expr body)

and this you can compile:

compile(expr, '<file>', 'eval')

Demo:

>>> import ast
>>> code = "if foo == 'bar': pass"
>>> tree = ast.parse(code, '<file>', 'exec')
>>> cond = tree.body[0].test
>>> expr = ast.Expression(cond)
>>> compile(expr, '<file>', 'eval')
<code object <module> at 0x1067f6230, file "<file>", line 1>
>>> foo = 'baz'
>>> eval(compile(expr, '<file>', 'eval'))
False
>>> foo = 'bar'
>>> eval(compile(expr, '<file>', 'eval'))
True
Sign up to request clarification or add additional context in comments.

2 Comments

Oh I didn't see there is a difference. Could I just pass cond to the constructor of ast.Expression, and use this object?
@user1839433: ah, my mistake; Expression() takes one expr field, not a list of them.

Your Answer

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.