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

Exploring class decorators

A class decorator is similar to the function decorator that we discussed earlier. Class decorators can be used to decorate, modify behavior, or debug a function, similar to a function decorator, which adds behavior to a function without actually modifying the function itself. A class decorator can be defined as a class by using two of its default or built-in methods: __init__ and __call__. Any variable initialized as part of the __init__ function of a class while creating an object instance of the class becomes a variable of the class itself. Similarly, the __call__ function of a class returns a function object. If we want to use a class as a decorator, we need to make use of the combination of these two built-in methods.

Let us look at what happens if we don’t use the call method. Look at the following piece of code:

class classdecorator:  
    def __init__(self,inputfunction):  
 ...