[Python-Dev] Dataclasses and correct hashability

Eric V. Smith eric at trueblade.com
Thu Feb 1 20:37:41 EST 2018


On 2/1/2018 8:29 PM, Elvis Pranskevichus wrote:
> On Thursday, February 1, 2018 8:21:03 PM EST Eric V. Smith wrote:
>> I should add: This is why you shouldn't override the default
>> (hash=None) unless you know what the consequences are. Can I ask
>> why you want to specify hash=True?
> 
> hash=None and compare=True leads to the same result, which, I think is
> even worse.

Have you actually tried that?

 >>> @dataclass(hash=None)
... class A:
...   foo: int = field(hash=True, compare=True)
...
 >>> hash(A(2))
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'A'

I believe the default hash=None on the class decorator does right thing. 
Please provide a counter-example.

 >> You're allowed to override the parameters to dataclasses.dataclass
 >> for cases where you know what you're doing. Consenting adults,
 >> and all.
 >
 > I don't agree with this.  You are comparing implicit dataclass
 > behavior with an explicit shoot-in-the-foot __hash__() definition.

I don't recommend ever specifying the decorator hash= parameter unless 
you have an unusual use case, in which case it's on you to get it right. 
There was recently a long python-dev discussion on this issue. I need to 
update the PEP to reflect it, but the advice still stands: you almost 
always want to use the default hash=None.

Do you have a use case for specifying a hash function on a class with 
mutable instances? Maybe you want frozen=True?

Eric


More information about the Python-Dev mailing list