Use __init_subclass__ hook to validate subclasses in Python

Redowan Delowar November 20, 2021
Source

At my workplace, we have a fairly large Celery config file where you're expected to subclass from a base class and extend that if there's a new domain. However, the subclass expects the configuration in a specific schema. So, having a way to enforce that schema in the subclasses and raising appropriate runtime exceptions is nice.

Wrote a fancy Python 3.6+ init_subclasshook to validate the subclasses as below. This is neater than writing a metaclass.

Running the script will print:

However, if we initialize the Sub class like this:

This will raise an error:

Test

Discussion in the ATmosphere

Loading comments...