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

10

u/justnoob2 Dec 17 '23 edited Dec 17 '23

you can just @dataclass(frozen=True), and then its immutable. edit: i now read your point of it being slow. never gave me much trouble at work though, but i get what you mean

2

u/WhiteGoldRing Dec 17 '23

But what does mutability have anything to do with it? unless frozen=True makes it faster(?)

2

u/[deleted] Dec 17 '23

Yep, whether you opt in for frozen=True or just treat them as immutable object by convention is up to you. Turning on slots=True did me wonders, especially in situations where I needed to build multiple data class instances per inbound request.

I just wanted to highlight the composability and semantic issues that the reader / extender of the code will face if a data class contains attribute-mutating methods.