Skip to content

Instantly share code, notes, and snippets.

@jsbueno
Created April 15, 2020 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsbueno/5a207e6a2c6c433a7549c78ba2edab7d to your computer and use it in GitHub Desktop.
Save jsbueno/5a207e6a2c6c433a7549c78ba2edab7d to your computer and use it in GitHub Desktop.
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