Chapter 24. Class Metaprogramming
Everyone knows that debugging is twice as hard as writing a program in the first place. So if you’re as clever as you can be when you write it, how will you ever debug it?
Brian W. Kernighan and P. J. Plauger, The Elements of Programming Style1
Class metaprogramming is the art of creating or customizing classes at runtime.
Classes are first-class objects in Python,
so a function can be used to create a new class at any time,
without using the class
keyword.
Class decorators are also functions, but designed to inspect, change,
and even replace the decorated class with another class.
Finally, metaclasses are the most advanced tool for class metaprogramming:
they let you create whole new categories of classes with special traits,
such as the abstract base classes we’ve already seen.
Metaclasses are powerful, but hard to justify and even harder to get right. Class decorators solve many of the same problems and are easier to understand. Furthermore, Python 3.6 implemented PEP 487—Simpler customization of class creation, providing special methods supporting tasks that previously required metaclasses or class decorators.2
This chapter presents the class metaprogramming techniques in ascending order of complexity.
Warning
This is an exciting topic, and it’s easy to get carried away. So I must offer this advice.
For the sake of readability and maintainability, you should probably avoid the techniques described in this chapter in application code.
Get Fluent Python, 2nd 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.