Inspecting Python code with abstract syntax trees
In this section, we will review and understand the code for a simple arithmetic addition example, and we will also further look into parsing the code and modifying it using abstract syntax trees.
Reviewing simple code using ast
In this section, let’s review simple code that adds two numbers, and let’s look at all the elements of the node, and also how the elements are organized in the tree. Let’s begin by writing code to assign two variables, a
and b
, with numerical values, and c
as the sum of a
and b
. Finally, let’s print the c
value. This is shown in the following code:
addfunc = """
a = 1098
b = 2032
c = a + b
print(c)
"""
We will now parse the preceding addfunc
and store the node in another variable called add_tree
:
add_tree = ast.parse(addfunc)
add_tree
The output of the parsed node is as follows:
<ast.Module at 0x19c9b2bf2e0>...