Created
June 30, 2021 15:13
-
-
Save plammens/2e84581834392d242643721268908541 to your computer and use it in GitHub Desktop.
Merge metaclasses ad-hoc to solve metaclass conflicts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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