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

Understanding the MRO of a class

In this section, let’s explore how methods are resolved in a class that has no inheritance specified within its code. A class by default in Python 3 is inherited by object. To understand how MRO works on a class that has no parent class, looking at it in its simplest form is the easiest approach. We will then see how MRO works on a class with single, multiple, and multilevel inheritance.

In this example, let’s create a class for a branch of ABC Megamart as follows:

  1. In the Branch class, let’s create attributes for branch ID, street, city, state and ZIP code, product, sales, and invoice. Let’s also create methods such as get_product (which returns the product), get_sales (which returns sales), and get_invoice (which returns the invoice). The following code represents the Branch class:
    class Branch:
        def __init__(self, branch_id, branch_street, 
            ...