Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate condition of if in python

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?

like image 659
user1839433 Avatar asked May 26 '26 17:05

user1839433


1 Answers

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
like image 64
Martijn Pieters Avatar answered May 28 '26 06:05

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!