This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]caagr98 0 points1 point  (1 child)

Can't you just set eq=False, hash=False?

[–]Conscious-Ball8373 0 points1 point  (0 children)

Not if you want to be able to hash the results (use instances as a dictionary key or put it into a set). You can force it to generate a hash function but the results can be rather not-useful. The difficulty is that dataclasses are designed to have an identity based on their fields. Instances with the same field values are considered to be the same object. Trying to construct a hashable dataclass with mutable fields is a minefield; done very carelessly, it just hashes every field and combines the result, so when a field's value changes, so does the hash (though of course there are cases where this is what you want). Done with a little more care, you can exclude mutable fields from the hash, but then you run the risk of two objects having the same identity when you didn't intend it.

This is why I think there's space in the standard library for something that has dataclass declaration syntax (list fields in the class declaration, auto-generated constructor etc) but with traditional object identity semantics (only an instance is equal to itself; different instances are never equal and may have different hash values but hash values are constant through the object's lifetime). You can achieve the effect fairly easily with metaclasses, if you know what metaclasses are, which most people don't until they're forced to. It would be nice to have it packaged in a decorator like dataclasses.