Reputation: 423
I want to create a code object that I would be able to reuse with eval
later on. I need to do this based on some ast
nodes I have programmatically generated, therefore I can't have code as a string passed to compile
function. How to construct a valid ast
node for compile? Below are couple of things I have tried:
tree = ast.parse("2+2")
exe = compile(tree.body[0], filename="", mode="eval")
TypeError: expected Expression node, got Expr
tree = ast.BinOp(left=ast.Num(n=2), right=ast.Num(n=2), op=ast.Add())
exe = compile(tree, filename="", mode="eval")
TypeError: expected Expression node, got BinOp
tree = ast.BinOp(left=ast.Num(n=2), right=ast.Num(n=2), op=ast.Add())
expr = ast.Expression(body=[tree])
ast.fix_missing_locations(expr)
exe = compile(expr, filename="", mode="eval")
TypeError: required field "lineno" missing from expr
Upvotes: 5
Views: 2110
Reputation: 106455
Your last attempt is close, but the body
of ast.Expression
should be a single expression, not a list of expressions.
Change:
expr = ast.Expression(body=[tree])
to:
expr = ast.Expression(body=tree)
so that eval(exe)
returns: 4
Upvotes: 5