Metaclasses

A class is an object, so it has a type. That type is the metaclass. From this one fact you can derive the Django ORM, pydantic and ABCs — and the understanding that nine times out of ten a metaclass is not needed.

L1 · 8 minL2 · 10 min📱 phoneverified · CPython 3.11, linux x86-64

1Predict

Commit to an output and a reason before you open the answer.

Snippet A
print(type(int))
print(type(type))
X = type("X", (object,), {"v": 1})
print(X, X().v)
<class 'type'>
<class 'type'>
<class '__main__.X'> 1
A class was created by calling a function. And the type of type is itself.
Snippet B
class Plugin:
    registry = []
    def __init_subclass__(cls, **kw):
        super().__init_subclass__(**kw)
        Plugin.registry.append(cls.__name__)

class A(Plugin): pass
class B(Plugin): pass
print(Plugin.registry)
['A', 'B']
The registry filled itself, with no metaclass and no decorator.
Snippet C
class Field:
    def __set_name__(self, owner, name):
        print("set_name", owner.__name__, name)

class M:
    f = Field()
set_name M f
The descriptor learned its own name at the moment the class was created — although nobody passed it in.
Snippet D
from abc import ABC, abstractmethod
class Base(ABC):
    @abstractmethod
    def go(self): ...

class OtherMeta(type): pass
class Conflict(Base, metaclass=OtherMeta): pass
TypeError: metaclass conflict: the metaclass of a derived
class must be a (non-strict) subclass of the metaclasses
of all its bases
An error at class declaration, before any use at all.

2Mechanism

From lesson 06 we know: class is an executable statement, and the collected dictionary of names is passed to the type's constructor. Here we call that constructor by its name.

A class is an object, so it has a type. The type of a class is called a metaclass. By default it is type.

type with three arguments creates a class: a name, a tuple of bases, a dictionary of names. The class statement is syntax for this call.

A metaclass is a class that inherits from type. By overriding its methods you wedge yourself either into the creation of the class or into the creation of instances.

Consequence 1 · the recursion stops at type itself

Snippet A. type(int) is type, because int was created by it. And type(type) is type again: the “object → its type” chain closes on itself, otherwise it would be infinite. This is the only place in the language where such a loop exists, and it was made precisely so that the model stays finite.

And since a class is created by a call, it can be created by hand at any moment — which is what every library that generates classes from a schema, a config or a database table does.

Consequence 2 · two different points of intervention

A metaclass gives two fundamentally different hooks, and they are regularly confused.

The metaclass's __new__ and __init__ are called when the class is created — once, when class executes. Structure checks, registration and transformation of declared fields go here.

The metaclass's __call__ is called when an instance is created: it is what then invokes the class's own __new__ and __init__. Hence the classic singleton — intercept __call__ and return the same object every time.

The mistake “put the logic into the wrong method” gives code that runs once or, conversely, on every call — and looks inexplicable until you remember that these are different moments in its life.

Consequence 3 · three levels of intervention, and the metaclass is the extreme one

Snippets B and C show what covers most real tasks without a metaclass.

__init_subclass__ is called on the nearest ancestor when a subclass is created — enough for plugin registries, checks for required attributes, automatic registration of handlers. __set_name__ is called on every descriptor in the class body and tells it its name and owner — that is how model fields learn what they were named.

The full ladder in increasing order of cost: a class decorator (receives the finished class, the simplest) → __init_subclass__ and __set_name__ (built-in hooks, inherited) → a metaclass (changes the creation process itself). Choose the leftmost thing that solves the task.

Consequence 4 · metaclasses conflict

Snippet D. A class has exactly one metaclass, and it must be a subclass of the metaclasses of all the bases. ABC uses ABCMeta; trying to add your own metaclass to an abstract base class gives a conflict at declaration.

The cure is inheritance — class MyMeta(ABCMeta) — but the fact itself matters more than the cure: a metaclass is a claim to a monopoly. A library that uses its own metaclass mixes badly with another one like it. That is exactly why __init_subclass__ was added in 3.6: it is inherited and does not conflict.

3Limits of the model

Where this stops holding

A metaclass is inherited. It applies to all subclasses automatically, and that cannot be switched off. A class that happened to inherit from something with a metaclass gets its behaviour in full.

__prepare__ is needed less often than it seems. It supplies the dictionary for the class body; historically it was used to remember the order of declaration. Since 3.7 an ordinary dictionary is ordered 🔒, and most such uses have fallen away — enum is a case in point.

The order of the hooks is fixed: the body runs → the metaclass creates the class → __set_name__ is called on descriptors → __init_subclass__ is called on the ancestor. Logic that depends on a different order will not work.

4Root

Root R2: everything is resolved at runtime, and a class is an ordinary object. A metaclass is not a separate feature but a direct consequence: since a class is an object, it has a type; since the type can be replaced, the creation process can be intercepted.

The mechanism appeared in 2001 together with the unification of types and classes, and for ten years remained an expert tool with a reputation for “deep magic”. The turning point came in 3.6: __init_subclass__ and __set_name__ took out of metaclasses the two tasks for which they were written nine times out of ten. Today a metaclass in application code is almost always a sign that the task can be solved more simply.

5Analogy

The closest exact analogy is CRTP in C++: a base template parameterized by its own descendant, which at instantiation knows about the descendant and can register it. That is exactly what __init_subclass__ does, only in C++ the work is done by the compiler, and in Python by the interpreter when it executes class.

The difference in price is telling. CRTP is free at runtime and expensive to diagnose: an error comes out as a two-page message. __init_subclass__ costs a call on every class declaration and is debugged with an ordinary print. The same technique, two different currencies.

6Questions a careful reader asks

Questions that come up on their own if you read closely. The answer is under the question.

If metaclasses are so powerful, why does almost nobody write them?

Because over ten years almost everything they were called in for moved into cheaper mechanisms.

The classic tasks of a metaclass: register a subclass in a registry, check that it has the required attributes, let descriptors know their names, insert generated methods. Today the first three have __init_subclass__ and __set_name__ (both since 3.6), and the fourth has a class decorator.

class Plugin:
    registry = []
    def __init_subclass__(cls, /, name=None, **kw):
        super().__init_subclass__(**kw)
        cls.name = name or cls.__name__.lower()
        Plugin.registry.append(cls)

class Csv(Plugin, name="csv"): pass
class Json(Plugin): pass
print([c.name for c in Plugin.registry])    # → ['csv', 'json']

This reads well, does not require explaining metaclasses to a newcomer and — most importantly — does not conflict. A metaclass is inherited, and a class cannot have two incompatible metaclasses: trying to inherit from ABC and from your own class with a metaclass gives TypeError: metaclass conflict. That is the one reason a metaclass in a library becomes a problem for its users.

When a metaclass is needed after all: to change the process of creating a class before it exists — substitute the namespace through __prepare__, override __call__ so that C() does not create a new object at all, or control type itself. All of this lives in enum, abc, the Django ORM and pydantic — that is, in libraries, not in application code.

Why is type its own type? Is that not a vicious circle?

The circle exists, but it is closed in C, not in Python — and no recursion happens at execution time.

print(type(1), type(int), type(type))
# → <class 'int'> <class 'type'> <class 'type'>
print(type.__class__ is type)        # → True

At interpreter startup the structures PyType_Type and PyBaseObject_Type are created as static C structures, and the ob_type field of type is simply filled with a pointer to itself. It is an assignment, not a computation — nobody is going to walk the chain.

The second half of the circle is the same: object is the base class of everything, and type is its subclass; at the same time type is the type of object. Both statements are true at once, and both are fixed by hand at initialization.

print(type.__mro__)          # → (type, object)
print(isinstance(object, type), issubclass(type, object))   # → True True

A practical point, not a curiosity: from “a class is an object too, and it has a type” it follows that the type of a class can be replaced — and that is the metaclass. Not a separate entity of the language but an ordinary application of R1 to classes themselves. If type were not an object, metaclasses would not exist, but separate rules for classes would have to be introduced — that is, a second rule instead of one.

__init_subclass__ or a class decorator — which to choose?

The difference is one thing: whether the behaviour is inherited.

__init_subclass__ fires automatically on every subclass, including those that will be written later and elsewhere. A decorator applies exactly where it was written and does not extend to subclasses.

def tag(cls):
    cls.tagged = True
    return cls

@tag
class Base: pass
class Child(Base): pass
print(Base.tagged, Child.tagged)     # → True True  (the attribute was inherited, but not the processing)

class Base2:
    def __init_subclass__(cls, **kw):
        super().__init_subclass__(**kw)
        cls.registered = True
class Child2(Base2): pass
print(hasattr(Base2, "registered"), Child2.registered)   # → False True

Note the second line: __init_subclass__ is not called for the base class itself — only for descendants.

The rule of choice. If every descendant must automatically get into a registry or pass a check — __init_subclass__. If you need a one-off transformation of a specific class (dataclass, functools.total_ordering, registering one handler) — a decorator: it is visible at the point of use and imposes nothing on descendants.

And a third option, often better than both: explicit registration by a call. register(Csv) one line below — boring, but it can be found by searching the code and it surprises nobody.

Bottom line. A class is an object, so it has a type, and that type is called a metaclass; by default it is type, which is its own type so that the chain does not run off to infinity. The class statement is syntax for calling type(name, bases, dict), so a class can be created by hand at any moment — every library that generates classes from a schema rests on this. A metaclass gives two different hooks: its __new__ fires when the class is created, its __call__ when an instance is created, and confusing them means getting inexplicable behaviour. But in application code a metaclass is almost always overkill: __init_subclass__ and __set_name__, which appeared in 3.6, cover registries and model fields, are inherited and do not conflict — whereas a class has exactly one metaclass, and it is a claim to a monopoly.
From here on — optional
counterfactualC++ templates and Java annotationsCode generation by the compiler versus class generation at runtime

C++ solves the same task — “generate code from a description” — with templates and CRTP, at compile time. Registering subclasses through CRTP looks almost like __init_subclass__, only it is unrolled by the compiler and costs nothing at runtime. The price: an error in a template gives unreadable diagnostics, and the generated code cannot be looked at; in Python a class can be printed and poked, but you pay with execution at import time.

Java took a third path: annotations plus processing at build time or reflection at runtime. Hence code generators in the build — something Python does not need, because for it “build” and “execution” are one and the same moment.

Three answers to the question “when to decide the structure of a class”: at compilation, at build, at import. Python chose the last and got flexibility at the price of declaration errors being visible only at startup.

🐛 bugYour own metaclass on top of ABCThe library already uses ABCMeta — the class stops being created, the error is at import

Structure validation was added through a metaclass. The whole module stopped importing.

class Validated(type):
    def __new__(mcls, name, bases, ns):
        assert "schema" in ns, f"{name} has no schema"
        return super().__new__(mcls, name, bases, ns)

class Model(SomeABC, metaclass=Validated):   # SomeABC inherits from ABC
    schema = {}
TypeError: metaclass conflict: the metaclass of a derived class
must be a (non-strict) subclass of the metaclasses of all its bases

Review lets it through because the metaclass is written correctly and works in isolation. What breaks is the joint: ABC brings ABCMeta along, and a class can have only one metaclass. What makes it especially unpleasant is that it fails at import, that is, it takes down the whole module, not a single test.

The formal cure is to inherit: class Validated(ABCMeta). But the right conclusion is different: checking structure does not need a metaclass at all.

class Model(SomeABC):
    def __init_subclass__(cls, **kw):
        super().__init_subclass__(**kw)
        assert hasattr(cls, "schema"), f"{cls.__name__} has no schema"

The hook is inherited, conflicts with nothing and works with anyone else's metaclass. The rule derived from consequence 4: a metaclass is a monopoly, and it is worth taking only when you cannot do without it.

⚡ techniqueA plugin registry without a metaclass__init_subclass__ instead of a metaclass: inherited, conflict-free, readable without preparation

The classic task “collect all subclasses into a registry” — and three ways to solve it, of which the worst is usually chosen.

class Handler:
    registry = {}
    def __init_subclass__(cls, *, event=None, **kw):
        super().__init_subclass__(**kw)
        if event:
            Handler.registry[event] = cls

class OnPush(Handler, event="push"): pass
class OnTag(Handler, event="tag"): pass

Note the keyword argument right in the list of bases: class OnPush(Handler, event="push"). It is not a trick — class accepts arbitrary keyword arguments and passes them to __init_subclass__. No metaclass is needed for this.

approachprice
a class decoratorthe simplest, but you must not forget to apply it
__init_subclass__fires by itself, inherited, conflict-free
a metaclassthe same, plus a monopoly and conflicts with other people's bases

When a metaclass is needed after all: when you have to change the class creation process itself — substitute the bases, rewrite the dictionary of names before the type is created, intercept the creation of instances through __call__. Everything else is covered by the first two rows of the table.

💻 terminalCheck it in the REPLFour snippets plus the order of the hooks and a singleton through __call__

Run the four snippets and check them against your prediction. Then:

class Meta(type):
    def __new__(mcls, n, b, ns): print("class new"); return super().__new__(mcls, n, b, ns)
    def __call__(cls, *a): print("call"); return super().__call__(*a)
class C(metaclass=Meta): pass
C(); C()
# How many times was each one printed, and why?

class D:
    x = Field()
    def __init_subclass__(cls): print("init_subclass")
class E(D): x = Field()
# In what order will __set_name__ and __init_subclass__ fire?

import enum
type(enum.Enum)
# Why does Enum have a metaclass rather than a decorator?

# Without code: why is __init_subclass__ not called
# for the class in which it is defined?

The first question is the key one: it separates the two moments from consequence 2 literally by the call count.

sourceenum, ABC and pydanticThree libraries where a metaclass is justified — and you can see exactly how

Lib/enum.py, EnumType. Here a metaclass really is necessary: it turns the ordinary names in the class body into member objects, forbids redefining members, and overrides __call__ so that Color(1) looks up an existing member instead of creating a new one. Both points from consequence 2 are used at once — a rare and honest case.

Lib/abc.py, ABCMeta. It counts the abstract methods when the class is created and substitutes __instancecheck__ so that registration of virtual subclasses works. Note _abc_registry built on weak references — the mechanism from lesson 09 in live form.

pydantic. It collects the model's fields from annotations at declaration time and builds a validator. Look at how in version 2 a large part of the work moved into __init_subclass__ and into a compiled core — the direction of travel is the same as in the standard library: from the metaclass into lighter hooks.

L2What exactly happens when class executesThe full sequence of calls and where each hook sits

From L1 you know about the two moments of intervention. Here: the exact sequence.

The order when the statement class C(B1, B2, metaclass=M, **kw) executes:

  1. The metaclass is determined: an explicit metaclass= or the most derived among the metaclasses of the bases. If there is none — the conflict from snippet D.
  2. M.__prepare__(name, bases, **kw) is called — it returns the dictionary in which the body will run.
  3. The class body runs in that dictionary as ordinary code.
  4. M(name, bases, ns, **kw) is called — that is, M.__call__ as defined by the metaclass's metaclass, and it invokes M.__new__ and M.__init__.
  5. Inside type.__new__: the MRO is computed, the type slots are filled, then __set_name__ is called on every object in the dictionary that has one.
  6. __init_subclass__ of the nearest ancestor is called — on the finished class.

Hence the answer to the question from the “Check it yourself” section: __init_subclass__ does not fire for the class in which it is defined, because it is looked up on the ancestors, and at the moment the class itself is being created it is not there yet.

A practical consequence for debugging: if a hook did not fire, the question is always “at which step”, and there are exactly six steps. type(C) shows the metaclass, C.__mro__ shows where __init_subclass__ was looked up, and a print inside __prepare__ confirms that the metaclass chosen is the one you expected.

L3Where this is in the CPython sourcestypeobject.c: type_new and type_call, step by step

Tag v3.11.15.

  • Objects/typeobject.c, type_new — class creation in full: choosing the metaclass, the MRO, walking the dictionary calling __set_name__, then __init_subclass__. The whole sequence from L2 can be read straight from there.
  • In the same file, type_call — what C() does: call __new__, check the type of the result, call __init__. Consequence 2 as thirty lines.
  • Python/ceval.c, the LOAD_BUILD_CLASS instruction, and the function builtin___build_class__ in Python/bltinmodule.c — how the compiler turns class into a call.
  • PEP 487 — the introduction of __init_subclass__ and __set_name__; the motivation says outright which uses of metaclasses they replace.
connectionsWhere this leadsL06, L04, L05 · the contrast with C++ templates and Java annotations
root R2 · Attributes are resolved at runtime, a namespace is a dict
← foundation L06 · Classes — the extension point promised there is taken apart here
← foundation L05 · dict and hashability — a class body is a dictionary, and its ordering cancelled half the uses of __prepare__
← foundation L04 · obj.x, end to end — __set_name__ is called on the descriptors from there
↔ contrast CRTP and C++ templates: the same task, solved by the compiler
↔ contrast Java annotations processed at build time — a third moment for making the decision
→ next L08 · Functions and decorators — a class decorator as the lightest level from consequence 3
not covered here How dataclass generates __init__ through exec — that is a decorator, not a metaclass; in L08
readingFurther readingPEP 487 🟥 · class creation 🟧 · “Python metaclasses” 🟦

Written by · The Python Canon