Advertisement
Advanced Python, Metaclasses & Class Customization

Why can't you freely mix two classes with different, incompatible metaclasses in multiple inheritance?

Short answer

When a class inherits from multiple bases with different metaclasses, Python must determine a single metaclass for the new class that is a subclass of all the bases' metaclasses (found via metaclass conflict resolution); if no such common metaclass exists, Python raises…

Save Python mock interview
Advertisement
AModel answer
When a class inherits from multiple bases with different metaclasses, Python must determine a single metaclass for the new class that is a subclass of all the bases' metaclasses (found via metaclass conflict resolution); if no such common metaclass exists, Python raises `TypeError: metaclass conflict`. This is why combining ABCMeta-based classes with other custom metaclasses sometimes requires defining a new metaclass that inherits from both.
class MetaA(type): pass
class MetaB(type): pass
class A(metaclass=MetaA): pass
class B(metaclass=MetaB): pass

try:
    class C(A, B): pass  # TypeError: metaclass conflict
except TypeError as e:
    print(e)
Real-world example
Combining a third-party ORM base class (using a custom metaclass) with an ABC-based interface sometimes forces you to define `class CombinedMeta(ORMMeta, ABCMeta): pass` and use it explicitly to resolve the conflict.
Likely follow-ups
  • How do you resolve a metaclass conflict manually?
  • Why does Python require metaclass compatibility across bases?
Related topics