typestar

__init_subclass__ in Python

A hook that runs when a subclass is defined — a registry without a metaclass.

class Plugin:
    registry = {}

    def __init_subclass__(cls, name=None, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.registry[name or cls.__name__.lower()] = cls


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


class Json(Plugin):
    pass


print(sorted(Plugin.registry))
print(Plugin.registry["csv"] is Csv)

How it works

  1. It is implicitly a classmethod on the parent.
  2. Keyword arguments in the class statement arrive here.
  3. Cheaper to read than a metaclass, and usually enough.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
297
Tokens
89
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 49 seconds.

Type this snippet

Step 2 of 3 in Class machinery, step 36 of 53 in Pythonic Python.

← Previous Next →