Hashability questions

Ian Kelly ian.g.kelly at gmail.com
Tue May 15 01:27:08 EDT 2012


On Mon, May 14, 2012 at 7:50 PM, Christian Heimes <lists at cheimes.de> wrote:
> Am 13.05.2012 21:11, schrieb Bob Grommes:
>> Noob alert: writing my first Python class library.
>>
>> I have a straightforward class called Utility that lives in Utility.py.
>>
>> I'm trying to get a handle on best practices for fleshing out a library.  As such, I've done the following for starters:
>>
>>   def __str__(self):
>>     return str(type(self))
>>
>> #  def __eq__(self,other):
>> #    return hash(self) == hash(other)
>>
>> The commented-out method is what I'm questioning.  As-is, I can do the following from my test harness:
>
> By the way, that's a dangerous and broken way to implement __eq__(). You
> mustn't rely on hash() in __eq__() if you want to use your object in
> sets and dicts. You must implement __hash__ and __eq__ in a way that
> takes all relevant attributes into account. The attributes must be read
> only, otherwise you are going to break sets and dicts.

Why?  I can't see any purpose in implementing __eq__ this way, but I
don't see how it's "broken" (assuming that __hash__ is actually
implemented somehow and doesn't just raise TypeError).  The
requirement is that if two objects compare equal, then they must have
the same hash, and that clearly holds true here.

Can you give a concrete example that demonstrates how this __eq__
method is dangerous and broken?

Cheers,
Ian



More information about the Python-list mailing list