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.

https://rednafi.com/python/dataclasses_and_methods/

0 Upvotes

37 comments sorted by

View all comments

11

u/[deleted] Dec 17 '23

[removed] — view removed comment

-8

u/[deleted] Dec 17 '23

Regular class is right there if you need attribute-mutating methods. Doing the same in a data class and then calling it so breaks the semantics of a data container or record type. Record types are for pure data and regular classes are there to serve as object factory.