Is there a way to convert a given Python abstract syntax tree (AST) to a source code?
Here is a good example of how to use Python's ast
module, specifically a NodeTransformer
. I was looking for a way to convert the resulting AST back to source, so the changes can be inspected visually.
ast is a module in the python standard library. Python codes need to be converted to an Abstract Syntax Tree (AST) before becoming “byte code”(. pyc files). Generating AST is the most important function of ast, but there are more ways one can use the module.
How to do using ast library, a = b + 3 or a = 3+b , both have same node type i.e. BinOp, you can validate variable “a” value and its node type. For each line of code, create AST node then compare value, node type and other parameters as well like operator, operand, function name, class name, index, etc… if required.
An Abstract Syntax Tree, or AST, is a tree representation of the source code of a computer program that conveys the structure of the source code. Each node in the tree represents a construct occurring in the source code.
The Python source tree contains an implementation of this: unparse.py in the Demo/parser directory
Editor's note: With the introduction of ast.unparse()
in Python 3.9, unparse.py has been removed, so the above link has been updated to point to 3.8.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With