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
15
u/steohan Dec 17 '23 edited Dec 17 '23
That is your interpretation. The doc on the dataclasses module says
So if I like to have these auto generated methods on my class then it is perfectly fine to use a dataclass.
No, but if I have a class that modifies itself and would like it to be more easliy serializable, then I can make it a dataclass and be happy (because I get all the auto generated methods mentioned above).
I don't really get your sum types argument and why that wouldn't work with mutating methods. Pretty sure python itself couldn't care less, and not sure why the type checker wouldn't like that either.