Sub topic 11
Metaclass selection and metaclass conflicts
This chapter assumes you can define a metaclass (a subclass of type) and pass metaclass= in a class line. It also assumes you know how super() works in multiple inheritance. Here you learn how Python decides which metaclass builds a class, and what to do when it cannot decide.
How Python picks the metaclass
Every class has exactly one metaclass. When Python runs a class statement, it first works out which one to use:
- If the class line has no
metaclass=and no bases, the metaclass istype. - If the class line gives
metaclass=M, start withM. Otherwise start with the type of the first base class. - Compare that candidate with the metaclass of every base class. The winner must be a subclass of all of them (or be the same class).
- If no single candidate is a subclass of all the others, Python raises
TypeError.
Selection in practice
The metaclass is inherited, and the most derived one wins. An explicit metaclass=type does not override an inherited metaclass.
class Meta(type):
pass
class SubMeta(Meta):
pass
class Base(metaclass=Meta):
pass
class Child(Base):
pass
class Special(Base, metaclass=SubMeta):
pass
class Plain(Base, metaclass=type):
pass
print(type(Child) is Meta) # True
print(type(Special) is SubMeta) # True
print(type(Plain) is Meta) # TrueChild inherits Meta from Base. Special asks for SubMeta, which is a subclass of Meta, so it is allowed. Plain asks for type, but Meta is more derived, so Meta wins.
Metaclass conflicts
A conflict happens when the base classes use metaclasses that are not related by inheritance. Neither is a subclass of the other, so Python cannot pick one.
class MetaA(type):
def __new__(mcls, name, bases, namespace, **kwargs):
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
cls.seen_by_a = True
return cls
class MetaB(type):
def __new__(mcls, name, bases, namespace, **kwargs):
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
cls.seen_by_b = True
return cls
class A(metaclass=MetaA):
pass
class B(metaclass=MetaB):
pass
try:
class C(A, B):
pass
except TypeError as exc:
print(exc)
class MetaC(MetaA, MetaB):
pass
class C(A, B, metaclass=MetaC):
pass
print(type(C) is MetaC, C.seen_by_a, C.seen_by_b) # True True TrueThe first attempt prints a message that begins "metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases". The fix is a new metaclass that inherits from both. It must be one metaclass that is a subclass of every base's metaclass.
Common sources of conflicts
Conflicts usually appear when you combine classes from different libraries. A well-known example is mixing an abc.ABC class (metaclass ABCMeta) with a class from a framework that has its own metaclass.
| Situation | Typical fix |
|---|---|
| Two libraries each define their own metaclass | Write a combined metaclass that subclasses both, as `MetaC` does above |
| You only need a registry or validation | Replace your metaclass with `__init_subclass__` so no second metaclass exists |
| One of the metaclasses is yours | Make it a subclass of the other metaclass, or drop it |
| The metaclass only post-processes the finished class | Use a class decorator, which does not affect selection |
Hooks that do not use a metaclass, such as __init_subclass__, __set_name__ and class decorators, cannot cause conflicts. This is a major reason to prefer them when they are enough.
Debugging a conflict
- Print
type(base)for each base class in the failing class line. - Check the full chain with
type(base).__mro__to see whether any metaclass is a subclass of another. - If the metaclasses are unrelated, decide whether to combine them or remove one.
class Mixin(metaclass=MetaA):
pass
class Model(metaclass=MetaB):
pass
for base in (Mixin, Model):
print(base.__name__, type(base).__name__)This prints Mixin MetaA and Model MetaB. These two metaclasses are unrelated, so class Both(Mixin, Model) would fail.
Exercise
Given class P(metaclass=MetaA) and class Q(P, metaclass=MetaB), where MetaA and MetaB are unrelated subclasses of type, what happens and how do you fix it?
Show answer
Python raises a TypeError (metaclass conflict). The explicit metaclass MetaB is not a subclass of MetaA, which is the metaclass of the base P. The fix is to define class MetaC(MetaA, MetaB): pass and write class Q(P, metaclass=MetaC). This works as long as both metaclasses call super() in their hooks. If MetaB could be written as a subclass of MetaA, that would also work.