Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert AST node to python code

Suppose I have the following string:

code = """
if 1 == 1 and 2 == 2 and 3 == 3:
    test = 1
"""

The following code converts that string in a AST.

ast.parse(code)

Then I have a tree like:

Module(body=[<_ast.If object at 0x100747358>])
  If(test=BoolOp(op=And(), values=[<_ast.Compare object at 0x100747438>, <_ast.Compare object at 0x100747a90>, <_ast.Compare object at 0x100747d68>]), body=[<_ast.Assign object at 0x100747e48>], orelse=[])

I want to know if there is a way to convert the object at.If into the string if 1 == 1 and 2 == 2 and 3 == 3:

I know it can be done traversing the children node, but it's getting too complicated that way.

like image 362
PepperoniPizza Avatar asked Oct 13 '16 20:10

PepperoniPizza


People also ask

How do I convert AST to code?

To build an ast from code stored as a string, use ast. parse() . To turn the ast into executable code, pass it to compile() (which can also compile a string directly).

Is AST built into Python?

AST . An abstract syntax tree can be compiled into a Python code object using the built-in compile() function.

What is AST Literal_eval in Python?

The ast. literal_eval method is one of the helper functions that helps traverse an abstract syntax tree. This function evaluates an expression node or a string consisting of a Python literal or container display.


2 Answers

Python 3.9 introduced ast.unparse which does exactly this, i.e. it reverses ast.parse. Using your example:

import ast

code = """
if 1 == 1 and 2 == 2 and 3 == 3:
    test = 1
"""

tree = ast.parse(code)
print(ast.unparse(tree))

This will print out:

if 1 == 1 and 2 == 2 and (3 == 3):
    test = 1

Note that there may be slight differences to the original input.

like image 99
Kalle Avatar answered Oct 21 '22 23:10

Kalle


ast.get_source_segment was added in python 3.8:

>>> import ast

>>> code = """
>>> if 1 == 1 and 2 == 2 and 3 == 3:
>>>     test = 1
>>> """
>>> node = ast.parse(code)
>>> ast.get_source_segment(code, node.body[0])
'if 1 == 1 and 2 == 2 and 3 == 3:\n    test = 1'
like image 10
Blane Avatar answered Oct 21 '22 21:10

Blane