Sub topic 11
Metaclass selection and metaclass conflicts
This chapter assumes you can define classes and use super(). It also assumes you know that a class statement ends in a call to a metaclass, as covered in the earlier chapters on type() and writing a first metaclass. Here you will learn how Python decides which metaclass to use, why that decision sometimes fails, and how to fix it.
How Python picks the metaclass
Every class has exactly one metaclass, which is the type of the class object. When Python runs a class statement, it picks that metaclass in three steps.
- If the class line has
metaclass=X,Xis the starting candidate. - Otherwise, if the class has bases, the starting candidate is
type(bases[0]). With no bases, it istype. - Python then compares the candidate against
type(base)for every base. It chooses the most derived metaclass, the one that is a subclass of all the others. If no such metaclass exists, Python raisesTypeError.
Step 2 means a subclass inherits its parent's metaclass without you writing anything:
class Meta(type):
pass
class Base(metaclass=Meta):
pass
class Child(Base):
pass
print(type(Child) is Meta) # TrueStep 3 means an explicit metaclass= can be less specific than what your bases require, and Python still picks correctly:
class Meta(type):
pass
class Base(metaclass=Meta):
pass
class Derived(Base, metaclass=type):
pass
print(type(Derived).__name__) # MetaHere type is a superclass of Meta. The winner is Meta, because it is a subclass of every candidate.
Inspecting the decision with types.prepare_class
The standard library exposes this logic as types.prepare_class(name, bases, kwds). It returns the winning metaclass, the namespace from __prepare__, and the remaining keyword arguments. It is the quickest way to check what Python will do without defining a class:
import types
class Meta(type):
pass
class Base(metaclass=Meta):
pass
meta, namespace, kwds = types.prepare_class('Child', (Base,))
print(meta.__name__) # Meta
print(namespace) # {}
print(kwds) # {}prepare_class also calls __prepare__ on the winner. That is why the namespace used for the class body comes from the most derived metaclass, not from the one you wrote on the class line.
What a metaclass conflict looks like
A conflict happens when two bases have metaclasses that are unrelated. Neither is a subclass of the other, so there is no valid winner.
class MetaA(type):
pass
class MetaB(type):
pass
class A(metaclass=MetaA):
pass
class B(metaclass=MetaB):
pass
try:
class C(A, B):
pass
except TypeError as exc:
print(exc)The message reads: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases. "Non-strict" means the derived metaclass may be one of the base metaclasses itself. It does not have to be a new class.
The error does not name the metaclasses involved. To diagnose it, print the type of each base:
print([type(b).__name__ for b in (A, B)]) # ['MetaA', 'MetaB']If the two names are unrelated classes, you have found the conflict. Check issubclass in both directions to confirm.
Conflicts you meet in real code
Hand-written metaclasses are not the usual cause. Conflicts mostly appear when you mix classes from different libraries. abc.ABC uses ABCMeta, and enum.Enum uses EnumType. Neither is a subclass of the other. Combining an abstract base with an enum, or either with a framework base class that has its own metaclass, can therefore raise this error. You did nothing wrong in your own code. The libraries simply made incompatible choices.
Fix 1: write a combined metaclass
The standard fix is a metaclass that inherits from all the conflicting ones, passed explicitly:
class MetaA(type):
pass
class MetaB(type):
pass
class A(metaclass=MetaA):
pass
class B(metaclass=MetaB):
pass
class MetaC(MetaA, MetaB):
pass
class C(A, B, metaclass=MetaC):
pass
print(type(C) is MetaC) # TrueMetaC is a subclass of both MetaA and MetaB, so it satisfies step 3. The same fix works for a real case, such as a registry metaclass combined with ABCMeta:
from abc import ABCMeta, ABC, abstractmethod
class RegMeta(type):
registry = {}
def __new__(mcls, name, bases, namespace, **kwargs):
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
mcls.registry[name] = cls
return cls
class Registered(metaclass=RegMeta):
pass
class Shape(ABC):
@abstractmethod
def area(self):
...
class RegABCMeta(RegMeta, ABCMeta):
pass
class Square(Shape, Registered, metaclass=RegABCMeta):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
print(Square(3).area()) # 9
print('Square' in RegMeta.registry) # TrueCombined metaclasses must cooperate
A combined metaclass only works if every parent metaclass calls super() in its hooks. RegMeta.__new__ above calls super().__new__(mcls, name, bases, namespace, **kwargs). Because the MRO of RegABCMeta is RegABCMeta, RegMeta, ABCMeta, type, that call reaches ABCMeta.__new__. If RegMeta.__new__ skipped super() and called type.__new__ directly, ABCMeta would never run and the abstract-method checks would silently stop working. Forward **kwargs as well, so class keyword arguments reach the metaclass that wants them.
The same rule applies to __init__, __call__ and __prepare__. Each should delegate upward.
Generating the combination automatically
If you write a base class that others will mix with arbitrary libraries, a helper can build the combined metaclass on demand:
def derive_meta(*bases):
metas = list(dict.fromkeys(type(b) for b in bases))
# drop any metaclass that is a superclass of another one in the list
metas = [m for m in metas
if not any(o is not m and issubclass(o, m) for o in metas)]
if len(metas) == 1:
return metas[0]
name = '_'.join(m.__name__ for m in metas)
return type(name, tuple(metas), {})
class MetaA(type):
pass
class MetaB(type):
pass
class A(metaclass=MetaA):
pass
class B(metaclass=MetaB):
pass
class C(A, B, metaclass=derive_meta(A, B)):
pass
print(type(C).__name__) # MetaA_MetaBThis removes the boilerplate but not the cooperation requirement. If the parent metaclasses do not call super(), the generated class fails in the same way a hand-written one would.
Fix 2: remove one of the metaclasses
Often one of the two metaclasses exists only for something a lighter hook can do. A registry or a validation check is the typical case. Rewriting it with __init_subclass__ leaves only one metaclass, and the conflict disappears:
from abc import ABC, abstractmethod
class Registered:
registry = {}
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
Registered.registry[cls.__name__] = cls
class Shape(ABC):
@abstractmethod
def area(self):
...
class Square(Shape, Registered):
def area(self):
return 4
print(sorted(Registered.registry)) # ['Square']Registered has no custom metaclass, so its type is plain type. Combining it with ABCMeta is never a conflict, because ABCMeta is a subclass of type. This is one of the strongest practical arguments for preferring __init_subclass__. It does not take up the one metaclass slot a class has.
Metaclasses that are not classes
The metaclass= argument can be any callable, not only a subclass of type. If it is not a class, Python skips the winner calculation and calls it with (name, bases, namespace, **kwargs):
def tagging(name, bases, namespace, **kwargs):
namespace['tag'] = name.upper()
return type(name, bases, namespace)
class A(metaclass=tagging):
pass
class B(A):
pass
print(type(A).__name__) # type
print(A.tag) # A
print(B.tag) # AThe function ran for A, but it returned an ordinary class whose type is type. A subclass looks at type(A), finds type, and never calls the function again. B.tag is just the value inherited from A. A function used as a metaclass therefore hooks one class only, not its subclasses. For subclass hooks, use a real type subclass or __init_subclass__.
Calling type() directly follows the same rules
Calling type(name, bases, namespace) also runs the winner calculation. If a base has a custom metaclass, type hands the work to it:
class Meta(type):
pass
class Base(metaclass=Meta):
pass
X = type('X', (Base,), {})
print(type(X).__name__) # MetaWith conflicting bases, type('C', (A, B), {}) raises the same TypeError as a class statement. Dynamic class creation does not bypass the rules.
Common mistakes
- Putting the metaclass argument on the wrong class.
class C(A, B, metaclass=MetaA)still fails withMetaAalone ifBuses an unrelatedMetaB. The explicit metaclass must be a subclass of every base's metaclass. - Expecting
metaclass=typeto reset the metaclass. It does not. The winner calculation still picks the most derived metaclass among the bases, as theDerivedexample showed. - Forgetting
super()in a metaclass hook. In a single-metaclass world this often works by accident. In a combined metaclass it silently skips a parent. - Writing
type.__new__(mcls, ...)instead ofsuper().__new__(...). The former hard-codes the next step in the chain and breaks cooperation.
Summary table
| Situation | What Python does | Your fix |
|---|---|---|
| No `metaclass=`, one base | Uses `type(base)` | Nothing |
| `metaclass=type` plus a base with `Meta` | Winner is `Meta` | Nothing |
| Two bases with unrelated metaclasses | `TypeError` | Combined metaclass, or remove one metaclass |
| `metaclass=` is a function | Calls it, skips selection | Use a `type` subclass if subclasses need the hook |
| `type(name, bases, ns)` with conflicting bases | `TypeError` | Same as for a class statement |
Exercise
A class Report(Printable, Exportable) fails with a metaclass conflict. type(Printable) is PrintMeta and type(Exportable) is ExportMeta, and neither metaclass inherits from the other. Write the class line that fixes it, and name the one requirement on PrintMeta and ExportMeta that makes the fix work.
Show answer
Define class ReportMeta(PrintMeta, ExportMeta): pass, then write class Report(Printable, Exportable, metaclass=ReportMeta). The fix works only if both PrintMeta and ExportMeta call super() in their hooks (such as __new__ and __init__) and forward **kwargs, so that every metaclass in the MRO runs.
Exercise
What does this print, and why? def m(name, bases, ns, **kw): ns['hit'] = True; return type(name, bases, ns), then class A(metaclass=m): pass, class B(A): ns_check = 1, print('hit' in vars(A), 'hit' in vars(B)).
Show answer
It prints True False. The function ran for A and put hit into its namespace. The function returned a plain class, so type(A) is type. B therefore uses type and never calls m, and hit is only inherited from A, not stored in vars(B).