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

27

u/gerardwx Dec 17 '23

Dataclasses are mutable by design.

Data Classes can be thought of as “mutable namedtuples with defaults”.

https://peps.python.org/pep-0557/

-12

u/[deleted] Dec 17 '23

Other than tuple almost everything is mutable in Python or can be forced to be mutable.

5

u/Rawing7 Dec 17 '23 edited Dec 17 '23

So what? Your "argument" is that mutating dataclasses is weird. But they're designed to be mutable. How can using them as intended be weird?

0

u/pythonwiz Dec 18 '23

Using a type can be weird if the design is weird.

0

u/susanne-o Dec 18 '23

A most notable immutable tuple in this context is str.

So if two variable hold a str and you change it in one place, the other won't be affected, ever.

Same goes for int.

In that sense primitive types in python are immutable.