Resolve Metaclass Compatibility across Bases
Core idea
For ordinary type-based metaclasses, Python selects a candidate compatible with every base metaclass and any explicit type-based metaclass. The selected candidate must be a subclass of all the candidates. If unrelated candidates have no such candidate among them, creation raises TypeError. A combined metaclass can sometimes resolve this, but its hooks must cooperate; combining names alone does not ensure semantic compatibility. Non-type callable metaclasses are a separate case.
class Audit(type): passclass StrictAudit(Audit): passclass Base(metaclass=Audit): passclass Strict(metaclass=StrictAudit): passclass Combined(Base, Strict): passprint(type(Combined).__name__)print(issubclass(type(Combined), Audit))StrictAudit is compatible with both base metaclasses and is already a candidate.
Detect and resolve an empty-hook conflict
class LeftMeta(type): passclass RightMeta(type): passclass Left(metaclass=LeftMeta): passclass Right(metaclass=RightMeta): passtry: class Bad(Left, Right): passexcept TypeError: print('conflict')class BothMeta(LeftMeta, RightMeta): passclass Good(Left, Right, metaclass=BothMeta): passprint(type(Good).__name__)The unrelated candidates conflict. BothMeta is explicitly supplied and inherits both; no extra hook behavior is needed in this example.
Common mistake
Do not assume changing base order fixes incompatible metaclasses. Check whether a base hook or decorator can replace one customization instead of combining complex metaclasses.
Practice
Change StrictAudit to inherit directly from type instead of Audit. Predict whether Combined can be created, then test and explain the result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Metaclass selection
Check your understanding of metaclass selection.
What is printed?
class M(type): passclass A(metaclass=M): passclass B(A): passprint(type(B) is M)What is printed?
class M(type): passclass N(M): passclass A(metaclass=M): passclass B(A,metaclass=N): passprint(type(B).__name__)What is required of a selected type-based metaclass?
What happens when no candidate satisfies that criterion?