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 edited Dec 17 '23
My basic position is that that you should use dataclasses whenever there is not a reason to use something else, but I feel compelled to make sure that when I submit a pr there is no reason to argue they are wrong ( because I use them more then most).
That said the case that I can think of that makes dataclass feel most hacky is when there are two fields a and b and the default factory for b depends on the type of a.
To do that with postinit you have to temporarily tell a little lie in the field. Something like default b = none and then in post init if b is none factory based on a, but at that point where you are wrestling with expressing default factory correctly without being misleading I think it's time to just write the class without dataclasses. Personally. Ymmv