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 ...

Get Python Essentials 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.