Exploring the ast library
In this section, we will explore the ast
Python library, which can be imported from Python 3 to analyze the Python code written by developers. We can also use it to modify the code through its abstract syntax tree at a metaprogramming level rather than modifying the syntax of the code itself. This helps in understanding how the code is syntactically represented and how the syntax tree of the code can be used to modify its behavior without modifying the original source code. We will look at some of the important functions of the ast
library, as those functions will be used throughout this chapter to understand the code from our core example.
Let’s start by importing the ast
library:
import ast
Once we import the library, we can look at analyzing a piece of code using this library. We will now create a variable named assignment
and assign a string format of the code to it:
assignment = "product_name = 'Iphone X'"
The...