{
"$type": "site.standard.document",
"canonicalUrl": "https://rednafi.com/python/use-init-subclass-hook-to-validate-subclasses/",
"description": "Validate subclass schemas at definition time with Python's __init_subclass__ hook, a cleaner alternative to metaclasses for enforcing structure.",
"path": "/python/use-init-subclass-hook-to-validate-subclasses/",
"publishedAt": "2021-11-20T00:00:00.000Z",
"site": "at://did:plc:fgtm2c26vfcj74rfmeggbyqj/site.standard.publication/3mnl6f7ob462z",
"tags": [
"Python",
"TIL"
],
"textContent": "At my workplace, we have a fairly large Celery config file where you're expected to subclass\nfrom a base class and extend that if there's a new domain. However, the subclass expects the\nconfiguration in a specific schema. So, having a way to enforce that schema in the\nsubclasses and raising appropriate runtime exceptions is nice.\n\nWrote a fancy Python 3.6+ __init_subclasshook__ to validate the subclasses as below. This\nis neater than writing a metaclass.\n\nRunning the script will print:\n\nHowever, if we initialize the Sub class like this:\n\nThis will raise an error:\n\nTest",
"title": "Use __init_subclass__ hook to validate subclasses in Python"
}