dataclasses-json icon indicating copy to clipboard operation
dataclasses-json copied to clipboard

Failed to call super class __init__ from the subclass __init__

Open mokarrom opened this issue 2 years ago • 2 comments

It looks like I can't override init method in a subclass and instantiate the subclass. Let's assume, my base class, Data is defined as follows:

@dataclass_json(undefined=Undefined.EXCLUDE)
@dataclass
class Data:
    id: int
    text: str

And ScoredData class inherits Data class as follows:

@dataclass_json(undefined=Undefined.EXCLUDE)
@dataclass
class ScoredData(Data):
    score: float

    def __init__(self, data: Data, score: float):
        super().__init__(data.id, data.text)
        self.score = score

Now, if I try to instantiate ScoredData as follows:

my_data = Data(1, "cse")
scored_data = ScoredData(data=my_data, score=0.5)
print(str(scored_data))

it complains TypeError: __init__() missing 1 required positional argument: 'data' Interestingly, if I remove undefined=Undefined.EXCLUDE, then it seems working :)

mokarrom avatar Aug 16 '21 20:08 mokarrom

Without undefined=Undefined.EXCLUDE it is working but fails following:

scored_data_str = ScoredData.schema().dumps(scored_data)
saved_score_data = ScoredData.schema().loads(scored_data_str)

assert scored_data == saved_score_data

It throws TypeError: __init__() got an unexpected keyword argument 'id'

mokarrom avatar Aug 17 '21 20:08 mokarrom

Underlined in #442 as one of the targets to take down (user code mutation) - should be fixed in v1.

george-zubrienko avatar Jul 20 '23 22:07 george-zubrienko