Python AST - merging two ASTs

920 Views Asked by At

Do you have any idea how can i merge two asts using python ast?
I would like to do something like this:

n1 = ast.parse(input_a)
n2 = ast.parse(input_b)
n = merge(n1,n2)

I would like create root n with childs n1 and n2.
Thanks in advance

1

There are 1 best solutions below

1
Robᵩ On BEST ANSWER

It appears you can do this:

n1.body += n2.body

But I can't find that documented anywhere.

Sample:

>>> a=ast.parse("i=1")
>>> b=ast.parse("j=2")
>>> a.body += b.body
>>> exec compile(a, "<string>", "exec")
>>> print i
1
>>> print j
2
>>>