What is the abstract syntax tree?

The AST module allows us to interact with Python code and modify it. The module is used by automation testing tools and code coverage tools to parse source code and find possible flaws and errors in the code.

The AST module library in Python provides a tree structure for the source code. In Python, AST is compiled into a code object using the built-in compile() function.

Abstract syntax tree diagram

The following diagram shows how Python converts a simple statement to its syntax tree.

AST for the expression 6*7-3

For each line of code, create an AST node and then compare the value, node type, and other parameters like operator, operand, function name, class name, index, etc.


Code

import ast
code = ast.parse("6 * 7 - 3")
print(ast.dump(code))
New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources