Chapter 40. Metaclasses

In the prior chapter, we explored decorators and studied various examples of their use. In this final technical chapter of the book, we’re going to continue our tool-builders focus and investigate another advanced topic: metaclasses.

In a sense, metaclasses simply extend the code-insertion model of decorators. As we learned in the prior chapter, function and class decorators allow us to intercept and augment function calls and class instance creation calls. In a similar spirit, metaclasses allow us to intercept and augment class creation—they provide an API for inserting extra logic to be run at the conclusion of a class statement, albeit in different ways than decorators. Accordingly, they provide a general protocol for managing class objects in a program.

Like all the subjects dealt with in this part of the book, this is an advanced topic that can be investigated on an as-needed basis. In practice, metaclasses allow us to gain a high level of control over how a set of classes works. This is a powerful concept, and metaclasses are not intended for most application programmers. Nor, frankly, is this a topic for the faint of heart—some parts of this chapter may warrant extra focus (and others might even owe attribution to Dr. Seuss!).

On the other hand, metaclasses open the door to a variety of coding patterns that may be difficult or impossible to achieve otherwise, and they are especially of interest to programmers seeking to write flexible APIs or programming ...

Get Learning Python, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.