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 tools for others to use. Even if you don’t fall into that category, though, metaclasses can teach you much about Python’s class model in general (as we’ll see, they even impact inheritance), and are prerequisite to understanding code that employs them. Like other advanced tools, metaclasses have begun appearing in Python programs more often than their creators may have intended.

As in the prior chapter, part of our goal here is also to show more realistic code examples than we did earlier in this book. Although metaclasses are a core language topic and not themselves an application domain, part of this chapter’s agenda is to spark your interest in exploring larger application-programming examples after you finish this book.

Because this is the final technical chapter in this book, it also begins to wrap up some threads concerning Python itself that we’ve met often along the way and will finalize in the conclusion that follows. Where you go after this book is up to you, of course, but in an open source project it’s important to keep the big picture in mind while hacking the small details.