osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Documentation of __hash__


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).

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.