Search code examples
pythonmergeabstract-syntax-treepython-ast

Python AST - merging two ASTs


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


Solution

  • 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
    >>>