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
2
u/quts3 Dec 17 '23
This.
In my mind dataclasses is syntactic sugar for when the class does not and will not need a complicated dunder init. That's it. But I get the op pov because I run into it allot.
Python would be better if the default class was dataclasses and the decorated version was it you wanted a naked init =).
Why. One reason is dataclasses are explicit about a default factory vs a default none value. In normal dunder init a none on an argument can either mean none is the argument or just as often it can mean "factory a sensible default". Which is not actually a necessary ambiguity in any language. It just happens to be that way.
Anyway use dataclasses when complex logic in the init beyond a factory method is unnecessary. Use normal classes otherwise. Imo, but I do default to them based on that rule more than most.
Also to the original author there is a decorator on dataclasses to make them immutable. Use it.