Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Decorator to enable a @DataClass to call __init__ on superclasses
#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