In the prior chapter, we explored decorators and studied various examples of their use. In this final chapter of the book, we’re going 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 sprit, 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. As such, 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 work. This is a powerful concept, and metaclasses are not intended for most application programmers (nor, frankly, the faint of heart!).
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, metaclasses can teach you much about Python’s class model in general. ...