Created
January 19, 2019 04:23
-
-
Save ktbarrett/1a72b7e7ea5a421b8312e93abd39a030 to your computer and use it in GitHub Desktop.
Python generalized type parameterization factory function
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
def Parameterize(cls, *mixins, **attributes): | |
mixin_prefix = ''.join((mixin.__name__ for mixin in mixins)) | |
parameterize = (f"{k}={v}" for k,v in attributes.items()) | |
parameter_suffix = f"({', '.join(parameterize)})" | |
bases = tuple((*mixins, cls)) | |
base_types = tuple(frozenset(type(t) for t in bases)) | |
base_typename = ''.join((t.__name__ for t in base_types)) | |
base_type = type(base_typename, base_types, {}) | |
return base_type(f"{mixin_prefix}{cls.__name__}{parameter_suffix}", bases, attributes) | |
class A(type): pass | |
class B(type): pass | |
class C(metaclass=A): pass | |
class D(metaclass=B): pass | |
E = Parameterize(C, D, a=1, b=2) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment