Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given an AST, is there a working library for getting the source?

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.

like image 754
Muhammad Alkarouri Avatar asked Sep 22 '10 22:09

Muhammad Alkarouri


People also ask

What is the AST library?

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 do you use AST?

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.

What is code AST?

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.


1 Answers

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.

like image 93
Ned Batchelder Avatar answered Sep 29 '22 00:09

Ned Batchelder