3

Lets say I have a dataclass that I need to be hashable.

To do this, the typical method of doing so using dataclasses is to set the frozen=True and eq=True parameters in the wrapper method, thus making the class safely hashable. This, however, also makes the attributes within the class immutable.

The dataclass wrapper, however, also defines an unsafe_hash parameter that creates an __hash__ method but does not make the attributes read-only like frozen=True would. The documentation warns though that this should only be set "if [the] class is logically immutable but can nonetheless be mutated".

What exactly does "logically immutable but can nonetheless be mutated mean"? When is it safe to mutate a dataclass that has unsafe_hash checked, if ever? What is an example for a class that correctly uses unsafe_hash?

M. Chak
  • 530
  • 3
  • 13
  • 1
    This [thread](https://stackoverflow.com/questions/52390576/how-can-i-make-a-python-dataclass-hashable-without-making-them-immutable) may point you in the right direction. – metatoaster May 26 '22 at 01:58
  • That does seem to help with my predicament. Thank you! – M. Chak May 26 '22 at 02:01
  • "When is it safe to mutate a dataclass that has unsafe_hash checked, if ever?" It isn't ever safe, if you are using those instances in a hash-based container. "Logically immutable" means that the objects are technically mutable, but are not *supposed* to be mutated. – juanpa.arrivillaga May 26 '22 at 02:25
  • IOW, if you need to mutate the objects, they shouldn't be hashable (unless their hash/equality isn't based on those mutable attributes, e.g. by default, all objects are hashable because `object.__hash__` and `object.__eq__` work based on *identity*) – juanpa.arrivillaga May 26 '22 at 02:26
  • In my case, the class will never be mutated while it is being used in a hashed structure. There was, however, one attribute that needed to be mutated prior to a certain method being called (that wasn't necessary to be included in the __hash__ or __eq__ methods). I wanted a better understanding of what exactly I was doing with the unsafe_hash method though just to make sure that was safe. – M. Chak May 26 '22 at 02:31

0 Answers0