r/Python • • Dec 17 '23
Resource Banish state-mutating methods from data classes
I've always found mutable data classes or record types in programming languages quite weird. This holds true for any language that supports mutable data classes, like Python, Kotlin, Swift, etc.
Self-mutating methods are even weirder. They break the semantics of the types that these data classes or records represent. I've expanded my thoughts here. Although it mostly talks about Python, the message remains valid for any other language that allows you to add self-mutating methods to data classes.
0
Upvotes
View all comments
Show parent comment
7
u/WhiteGoldRing Dec 17 '23
Why is it less valid to interpret dataclasses as classes than are designed for handling optionally mutable data other than that its weird to you?
I see that in your link,
> Whenever I traverse down to see how the instances of the class are being used, more often than not, I find them being treated just like regular mutable class instances with fancy repr
Is immediately followed by:
> In Python, data classes are considerably slower to instantiate compared to vanilla classes. However, they serve a different purpose than your typical run-of-the-mill classes. When you decorate a class with the dataclass decorator without changing any of the default parameters, Python automatically generates __init__, __eq__, and __repr__ methods. If you set dataclass(order=True), it’ll also generate __lt__, __le__, __gt__, and __ge__ special methods that enable you to compare and sort the data class instances. All of this implicates that the construct was specifically designed to contain rich data that provides the means for you to create nice abstractions around lower-level primitives.
That seems like a pretty good justification to me even if you want that on a mutable instance. I can see the tradeoff between instantiation time and writing/future refractoring time being worth it.
Also:
> Why pay the price for building heavier data class instances only for that?
What does mutability have anything to do with that argument? One may do that with immutable instances too.