Types and contracts
What are metaclasses?
On this page
A metaclass controls aspects of class creation and behaviour. Python’s usual metaclass is type. A custom metaclass can validate declarations when a class is created. For simple subclass registration, consider __init_subclass__ first, since combining independently chosen metaclasses can introduce conflicts.
Worked example
Pythonclass OperationType(type):
def __new__(meta, name, bases, fields):
if "verb" not in fields:
raise TypeError("Every operation needs a verb")
return super().__new__(meta, name, bases, fields)
class Archive(metaclass=OperationType):
verb = "archive"
assert type(Archive) is OperationTypeExplore class relationships in the OOP Playground