2 ms·
Python is a multi-paradigm language. And not only that, I think there are many reasons to want to continue having non-dataclass classes. Dataclass fits best wi
by kzrdude 4y ago
Python is a multi-paradigm language.
And not only that, I think there are many reasons to want to continue having non-dataclass classes. Dataclass fits best with record-type data and not with encapsulated data or classes with mostly private attributes.
- HelloNurse 4y agoThe Python baseline is that a class does not know, and doesn't pretend to know, what attributes it could contain, everything is welcome unless extra code is added to repress rogue assignments. Trivial getters and setters, __init__ methods that copy their parameters to members of the same name, and other boring Java-like patterns are certainly served well by convenience tools like the attrs library or dataclasses, but distinguishing records from serious classes requires significant skill.
- eru 4y ago> [...], everything is welcome unless extra code is added to repress rogue assignments. I think slots do that, don't they?
- HelloNurse 4y agoYes, and dataclasses offer an even nicer notation.
- kzrdude 4y agoDataclasses make it very easy to define such classes indeed but they don't disallow extra attributes. So they really compose with a lot of other techniques
- packetlost 4y agoI'm not sure what you mean here, GP was saying dataclasses themselves don't prevent rogue assignments, but they have a nicer syntax for generating a `__slots__` automatically based on type-hints/class attributes which absolutely does.
- kzrdude 4y agoI see, new in Py 3.10 and new to me
- TomSwirly 4y ago> I think there are many reasons to want to continue having non-dataclass classes. Even just one would help us evaluation your claim! > Dataclass fits best with record-type data and not with encapsulated data or classes with mostly private attributes. How does it "not fit"? How would you know if a class were a datalclass? Would it break something? For me, not having to write a constructor is a small win right away, having the class have a useful `str` representation is nice, automatically comparable and hashable are nice, I can also make immutable classes which is very nice, etc, etc. Unless you really have no constructors of visible members, what's the drawback? I don't use `dataclasses` everywhere but more and more when I start any class I make it a `dataclass`.