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

32

u/steohan Dec 17 '23

Am I missing it or does you text not contain any argument, why doing that is bad? Seems to me like your argument is just 'that is not what I think it is meant for so you shouldn't do that'. Just becaues it might not be a good idea for the few usecases that you are using it for doesn't mean that it is a bad idea in general. There are plenty of good reasons to use a dataclass for a normal object, e.g., benefiting from easier serealization and deserialization. Reducing boiler plate. Or becaues you want to use the introspection features that are offered by dataclasses. Also, having mutable dataclasses makes a lot of sense and it makes perfect sense to have such a mutating method as a member instead of a stand alone function.

-7

u/[deleted] Dec 17 '23

It breaks semantics in the sense that data classes are designed for handling data. If you're not performing any comparisons between instances, putting them in another container, or treating them as data, using them doesn't make sense. It mostly implies that you need objects, and regular classes serve as object builders.

In the case of serializability, you're not modifying anything. So it's acceptable to add methods like that since they don't prevent you from composing types like SomeType = OtherType | AnotherType. The issue arises when you introduce attribute-mutating methods because doing so transforms the class into an object builder rather than a data builder. It's akin to using hashmaps for sequential data—sure, it works, but it's awkward.

3

u/thedeepself Dec 17 '23

data classes are designed for handling data.

All classes handle data don't they? In fact I think we would both agree that object oriented programming is about unifying data with the methods to operate on it.

The big win with data classes is that a large number of things that you would have to do with normal classes are handled automatically.

I cannot think of a single reason that one should ever use the old style python classes over data classes. But personally for me even data classes are not good enough I prefer traitlets myself.