If you don't add any more fields to your subclass is there a need to add the @dataclass
decorator to it and would it do anything?
If there is no difference, which is the usual convention?
from dataclasses import dataclass
@dataclass
class AAA:
x: str
y: str
...
# decorate?
class BBB(AAA):
...
From documentation, dataclasses
source code and experimenting with class instances, I don't see any difference, even if new fields are added to a subclass1.
If we are talking conventions, then I would advise against decorating a subclass. Class BBB
's definition is supposed to say "this class behaves just like AAA
, but with these changes" (likely a couple of new methods in your case).
Re-decorating BBB
:
AAA
: you might theoretically switch to another library for dataclassing or decide to use @dataclass
with non-default parameters, and that'd require maintaining subclass as well (for no good reason).1 As Andrius corrected me, if you add new fields in a subclass, you'll encounter the following problem:
>>> class BBB(AAA):
... z: str
...
>>> BBB('a', 'b', 'c')
Traceback (most recent call last):
File "<input>", line 1, in <module>
BBB('a', 'b', 'c')
TypeError: AAA.__init__() takes 3 positional arguments but 4 were given
Original question specifically says that new fields won't be added, so this is just a correction of my initial answer.