I have a dataclass Data
which holds data.
I would like a subclass PositiveData
, which is meant to distinguish positive data.
Here is an attempt:
@dataclass(frozen=True)
class Data:
id: int
value: float
class PositiveData(Data):
def __new__(cls, *args, **kwargs):
obj = super().__new__(cls, *args, **kwargs)
assert obj.value > 0
return obj
x = Data(id=1, value=2)
y = PositiveData(1, value=2)
The call to PositiveData
fails with error:
TypeError: object.__new__() takes exactly one argument (the type to instantiate)
Is there a way to subclass Data
with a check in the constructor? Thank you.
I asked a similar question here: Subclass of dataclass, with some assertions. The difference is that here I would like the subclass to not have the dataclass decorator. It seems to cause some strange problems in my specific usecase.