Browse OOP reference
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

Python
class 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 OperationType

Python data model

Explore class relationships in the OOP Playground

What is a method?What is a class?What is method overloading?

All OOP questions

Search ObjectFAQ