Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python __init_subclass__: validate declarations without a custom metaclass

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

Init_subclass is a class hook invoked when a subclass is created, allowing a base to validate subclass declarations.

Download Python source kit

Operation contract

The parser base consumes one class keyword and forwards remaining keywords through super. An accepted subclass gets an explicit wire name. A declaration with no valid name raises during class creation. This avoids a custom metaclass for a simple invariant while leaving a normal constructor and method lookup.

Failure and ownership boundary

The hook executes during class construction and is not a transaction across every cooperating base. Registering globally inside it can publish too early if a later hook fails. This fixture validates and assigns only the new class; it has no external registry. Multiple bases must agree on forwarding keywords. Python super and method resolution: cooperate across mixins and Python metaclasses: validate a class before registering its wire format expose those tradeoffs.

Working program

python
class ReceiptParser:
    def __init_subclass__(cls, *, wire_name=None, **options):
        super().__init_subclass__(**options)
        if not isinstance(wire_name, str) or not wire_name or len(wire_name) > 32:
            raise ValueError("wire name required")
        cls.wire_name = wire_name

class MinorParser(ReceiptParser, wire_name="receipt-minor"):
    pass

print(MinorParser.wire_name)
try:
    class UnnamedParser(ReceiptParser):
        pass
except ValueError:
    print("unnamed declaration rejected")

Output

Output
receipt-minor
unnamed declaration rejected

Costs and limits

The hook validates a bounded string once per class declaration. Classes remain ordinary objects; this check supplies neither runtime payload validation nor a code-execution sandbox.

Common Mistakes

  • Forward keywords through cooperative hooks rather than dropping them.
  • A successful declaration does not validate future request payloads.

Connected lessons

Python super and method resolution: cooperate across mixins, Python metaclasses: validate a class before registering its wire format, Python ABC: prevent construction of an incomplete implementation.

python
subclass-hooks
Storage details