Created
April 15, 2020 20:44
-
-
Save jsbueno/5a207e6a2c6c433a7549c78ba2edab7d to your computer and use it in GitHub Desktop.
Decorator to enable a @DataClass to call __init__ on superclasses
This file contains 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
#Decorator to enable a @dataclass to call __init__ on superclasses | |
from functools import wraps | |
def colaborative(cls): | |
if not hasattr(cls, "__dataclass_fields__") or not "__init__" in cls.__dict__: | |
return cls | |
cls._dataclass_init = cls.__init__ | |
super_ = cls.__mro__[1] | |
@wraps(cls.__init__) | |
def __init__(self, *args, **kw): | |
# use inspect.signature stuff to proper retrieve 'args' into dataclass kw if needed, else: | |
dataclass_kw = {} | |
for key, value in list(kw.items()): | |
if key in cls.__annotations__: | |
dataclass_kw[key] = kw.pop(key) | |
self._dataclass_init(**dataclass_kw) | |
super_.__init__(self, *args, **kw) | |
cls.__init__ = __init__ | |
return cls | |
""" | |
# example: | |
class A: | |
def __init__(self, d): | |
print(d) | |
@colaborative | |
@dataclass | |
class B(A): | |
c: int | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment