
On Sat, Apr 23, 2022 at 10:53 AM Pablo Alcain <pabloalcain@gmail.com> wrote:
Overall, I think that not all Classes can be thought of as Dataclasses and, even though dataclasses solutions have their merits, they probably cannot be extended to most of the other classes.
Absolutely. However, this is not an "all Classes" question. I don't think of dataclasses as "mutable namedtuples with defaults" at all. But do think they are for classes that are primarily about storing a defined set of data. I make heavy use of them for this, when I am adding quite a bit of ucntionatily, but their core function is still to store a collection of data. To put it less abstractly: Dataclasses are good for classes in which the collection of fields is a primary focus -- so the auto-generated __init__, __eq__ etc are appropriate. It's kind of a recursive definition: dataclasses work well for those things that data classes' auto generated methods work well for :-) If, indeed, you need a lot of custom behavior for teh __init__, and __eq__, and ... then datclasses are not for you. And the current Python class system is great for fully customized behaviour. It's quite purposeful that parameters of the __init__ have no special behavior, and that "self" is explicit -- it gives you full flexibility, and everything is explicit. That's a good thing. But, of course, the reason this proposal is on the table (and it's not the first time by any means) is that it's a common pattern to assign (at least some of) the __init__ parameters to instance attributes as is. So we have two extremes -- on one hand: A) Most __init__ params are assigned as instance attributes as is, and these are primarily needed for __eq__ and __repr__ and on the other extreme: B) Most __init__ params need specialized behavior, and are quite distinct from what's needed by __eq__ and __repr__ (A) is, of course, the entire point of dataclasses, so that's covered. (B) is well covered by the current, you-need-to-specify-everything approach. So the question is -- how common is it that you have code that's far enough toward the (A) extreme as far as __init__ params being instance attributes that we want special syntax, when we don't want most of the __eq__ and __repr__ behaviour. In my experience, not all that much -- my code tends to be on one extreme or the other. But I think that's the case that needs to be made -- that there's a lot of use cases for auto-assigning instance attributes, that also need highly customized behaviour for other attributes and __eq__ and __repr__. NOTE: another key question for this proposal is how you would handle mutable defaults -- anything special, or "don't do that"? -CHB -- Christopher Barker, PhD (Chris) Python Language Consulting - Teaching - Scientific Software Development - Desktop GUI and Web Development - wxPython, numpy, scipy, Cython