More complex metaprogramming with metaclasses
In some cases, the default features built into a class aren't appropriate for our particular application. We can see a few common situations where we might want to extend the default behavior of object construction.
- We can use a metaclass to preserve some of the original source code that defined a class. By default, each class object uses
dict
to store the various methods and class-level attributes. We might want to use an ordered dictionary to retain the original source code ordering for class-level attributes. An example of this is shown in the Python Standard Library, section 3.3.3.5. - The abstract base classes (ABC) rely on a
metaclass __new__()
method to confirm that the concrete subclass is complete when we attempt to create an instance of the class. If we fail to provide all of the required methods in a subclass of an ABC, we can't create an instance of that subclass. - Metaclasses can be used to simplify object serialization. A metaclass...