Book Image

Metaprogramming with Python

By : Sulekha AloorRavi
Book Image

Metaprogramming with Python

By: Sulekha AloorRavi

Overview of this book

Effective and reusable code makes your application development process seamless and easily maintainable. With Python, you will have access to advanced metaprogramming features that you can use to build high-performing applications. The book starts by introducing you to the need and applications of metaprogramming, before navigating the fundamentals of object-oriented programming. Next, you will learn about simple decorators, work with metaclasses, and later focus on introspection and reflection. You’ll also delve into generics and typing before defining templates for algorithms. As you progress, you will understand your code using abstract syntax trees and explore method resolution order. This Python book also shows you how to create your own dynamic objects before structuring the objects through design patterns. Finally, you will learn simple code-generation techniques along with discovering best practices and eventually building your own applications. By the end of this learning journey, you’ll have acquired the skills and confidence you need to design and build reusable high-performing applications that can solve real-world problems.
Table of Contents (21 chapters)
1
Part 1: Fundamentals – Introduction to Object-Oriented Python and Metaprogramming
4
Part 2: Deep Dive – Building Blocks of Metaprogramming I
11
Part 3: Deep Dive – Building Blocks of Metaprogramming II

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&gt...