0

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

Stevoisiak
  • 23,794
  • 27
  • 122
  • 225
Kapucko
  • 343
  • 3
  • 11
  • Don't you need to specify the type of nodes that you have? it seems like this would be highly dependent on `input_a` and `input_b`. – mgilson May 06 '13 at 19:33
  • for example, both inputs can be definition of function and i need to merge this two asts into one. I dont want to call ast parser on both together, because if one of them is non valid, i dont get any output... – Kapucko May 06 '13 at 19:40

1 Answers1

2

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
>>> 
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Hi, am unable to find the method ( body() ). I am creating translation unit using index.parse('my_Input_file') what is the ast in the solution? – anoop Apr 15 '17 at 23:52