Documentation of __hash__

klauck2 at gmail.com klauck2 at gmail.com
Tue Feb 11 05:23:45 EST 2020


On Friday, February 7, 2020 at 4:30:23 PM UTC+1, Random832 wrote:
> On Fri, Feb 7, 2020, at 10:14, Richard Damon wrote:
> > On 2/6/20 2:13 PM, klauck2 at gmail.com wrote:
> > > The default __eq__ method (object identity) is compatible with all (reasonable) self-defined __hash__ method.
> > >
> > > Stefan
> > 
> > If __eq__ compares just the id, then the only hash you need is the 
> > default that is also the id. If you define a separate hash function, 
> > which uses some of the 'value' of the object, then presumably you intend 
> > for objects where that 'value' matches to be equal, which won't happen 
> > with the default __eq__.
> 
> I think Stefan's point is that, no matter how questionable the intent may sound, any deterministic __hash__ doesn't technically violate the hash/eq relationship with the default __eq__, because hash(x) will still be equal to hash(x). Only defining __eq__ can create the problem where x == y but hash(x) != hash(y).

Yes, this is my question.

> 
> The purpose of this rule is to save you from having to override the default __hash__ with something that will only raise an exception when you do not intend your class to be hashable.

If I do not intend my class to be hashable, I will set __hash__ to None (according to the documentation).




More information about the Python-list mailing list