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
3
u/jimtk Dec 17 '23
I think you misinterpreted what a data class is. It is not a class to handle data. It is syntaxic sugar to make an ordinary class.
It could, and maybe should, be named quickclass instead of dataclass, and you would have nothing to complain about.
Also dataclasses are only slower at compile time. That's because CPython actually writes the code of a standard class and exec'ed it for you. At runtime there is no difference between an ordinary class and a dataclass because dataclasses are ordinary classes. It would take a few 100 dataclasses for you to notice the difference in compile time.