PythiloLesson 17 of 30 · progress kept in this browser

Class hooks and metaclasses

A class can react whenever it is subclassed. Python calls __init_subclass__ on the parent with the new class as cls, and passes it any keyword arguments from the class line.

class Plugin:
    registry = {}

    def __init_subclass__(cls, key, **kw):
        super().__init_subclass__(**kw)
        Plugin.registry[key] = cls

class Csv(Plugin, key="csv"):
    pass

class Json(Plugin, key="json"):
    pass

print(Plugin.registry)

This covers most needs: registering plugins, checking that a subclass defines what it must, or filling in defaults.

Your task

Give Command an __init_subclass__ that takes a keyword name and registers each subclass in Command.registry, raising TypeError if the subclass has no run method or the name is already taken. dispatch(name) creates the registered command and returns its run() result, raising KeyError for unknown names.