I want to have an instance of class registered when the class is defined. Ideally the code below would do the trick.
registry = {}
def register( cls ):
In python 3.6 simpler customization of class creation was introduced (PEP 487).
An
__init_subclass__hook that initializes all subclasses of a given class.
Proposal includes following example of subclass registration
class PluginBase:
subclasses = []
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.subclasses.append(cls)
In this example,
PluginBase.subclasseswill contain a plain list of all subclasses in the entire inheritance tree. One should note that this also works nicely as a mixin class.