Skip to content

Instantly share code, notes, and snippets.

@plammens
Created June 30, 2021 15:13
Show Gist options
  • Save plammens/2e84581834392d242643721268908541 to your computer and use it in GitHub Desktop.
Save plammens/2e84581834392d242643721268908541 to your computer and use it in GitHub Desktop.
Merge metaclasses ad-hoc to solve metaclass conflicts
from typing import Type, Optional
def merge_metaclasses(*bases: Type, metaclass: Optional[Type] = None) -> Type:
"""
Make an ad-hoc metaclass to resolve conflicts in class declarations.
Makes a metaclass that inherits from all of the metaclasses involved in a class
declaration: the metaclasses of the bases and the explicit metaclass. The
inheritance order is the explicit metaclass first and then the bases'
metaclasses, in order.
"""
metaclasses = []
if metaclass is not None:
metaclasses.append(metaclass)
for cls in bases:
mcs = type(cls)
if mcs not in metaclasses:
metaclasses.append(mcs)
name = "_".join(mcs.__name__ for mcs in metaclasses)
return type(name, tuple(metaclasses), {})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment