Automatically registering a plugin system
One of the most common uses of metaclasses is to have classes automatically register themselves as plugins/handlers. Examples of these can be seen in many projects, such as web frameworks. Those codebases are too extensive to usefully explain here though. Hence, we'll show a simpler example showing the power of metaclasses as a self-registering plugin
system:
>>> import abc >>> class Plugins(abc.ABCMeta): ... plugins = dict() ... ... def __new__(metaclass, name, bases, namespace): ... cls = abc.ABCMeta.__new__(metaclass, name, bases, ... namespace) ... if isinstance(cls.name, str): ... metaclass.plugins[cls.name] = cls ... return cls ... ... @classmethod ... def get(cls, name): ... return cls.plugins[name] >>> class PluginBase(metaclass=Plugins): ... @property ... @abc.abstractmethod ... def name(self): ... ...