In this lesson, you will learn how to resolve the TypeError that occurs when attempting to inherit from multiple classes that each use a different metaclass.
The Conflict
In Python, every class has a metaclass (the default being type). When you define a class that inherits from multiple parents, Python must determine the metaclass for your new class. If parent A uses MetaA and parent B uses MetaB, Python cannot automatically decide which metaclass should govern the child. Because a class can only have one metaclass, attempting this directly triggers a Metaclass conflict.
The Solution: Creating a Derived Metaclass
To resolve this, you must create a new metaclass that inherits from both MetaA and MetaB. By creating a "unified" metaclass, you provide a single parent that satisfies the requirements of both branches of your inheritance tree.
class MetaA(type): pass
class MetaB(type): pass
class A(metaclass=MetaA): pass
class B(metaclass=MetaB): pass
# This would normally raise a TypeError:
# class Child(A, B): pass
# We solve this by creating a combined metaclass:
class CombinedMeta(MetaA, MetaB):
pass
class Child(A, B, metaclass=CombinedMeta):
pass
Why this works
When you define CombinedMeta(MetaA, MetaB), you are essentially telling Python that your new class is compatible with the constraints of both parent metaclasses. During class creation, Python checks the Method Resolution Order (MRO) of the metaclasses. As long as you provide a metaclass that is a subclass of all the metaclasses used by your parents, Python’s inheritance machinery can successfully construct the class.
If the metaclasses are incompatible (i.e., they define conflicting __new__ or __init__ logic that cannot coexist), you may need to override those methods in your CombinedMeta to explicitly resolve the logic or delegate to super(). However, for most organizational metaclasses, simple inheritance is sufficient to bypass the conflict.
Key Takeaway: To resolve metaclass conflicts, explicitly define a new metaclass that inherits from all conflicting parent metaclasses to create a unified hierarchy.