Chapter 15. Metaclasses

A metaclass is to a class what a class is to an instance; that is, a metaclass is used to create classes, just as classes are used to create instances. And just as we can ask whether an instance belongs to a class by using isinstance(), we can ask whether a class object (such as dict, int, or SortedList) inherits another class using issubclass().

The simplest use of metaclasses is to make custom classes fit into Python’s standard ABC hierarchy. For example, to make SortedList a collections. Sequence, instead of inheriting the ABC (as we showed earlier), we can simply register the SortedList as a collections.Sequence:

class SortedList:    ...collections.Sequence.register(SortedList)

After the class is defined ...

Get Advanced Python 3 Programming Techniques now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.