I have a dataclass with (kind of) a getter method.
This code works as expected:
from dataclasses import dataclass
@dataclass()
class A:
def get_data(self):
# get some values from object's fields
# do some calculations
return "a calculated value"
@dataclass()
class B(A):
def get_data(self):
data = super().get_data()
return data + " (modified)"
b = B()
print(b.get_data()) # a calculated value (modified)
However, if I add slots=True
, I get a TypeError
:
from dataclasses import dataclass
@dataclass(slots=True)
class A:
def get_data(self):
return "a calculated value"
@dataclass(slots=True)
class B(A):
def get_data(self):
data = super().get_data()
return data + " (modified)"
b = B()
print(b.get_data()) # TypeError: super(type, obj): obj must be an instance or subtype of type
The error vanishes if I use the old-style super(), contrary to pep-3135:
from dataclasses import dataclass
@dataclass(slots=True)
class A:
def get_data(self):
return "a calculated value"
@dataclass(slots=True)
class B(A):
def get_data(self):
data = super(B, self).get_data()
return data + " (modified)"
b = B()
print(b.get_data()) # a calculated value (modified)
Why does this happen and how to fix it the right way?