On Tue, May 15, 2012 at 3:27 PM, Ian Kelly <[email protected]> wrote:
> 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?
Its brokenness is that hash collisions result in potentially-spurious
equalities. But I can still invent a (somewhat contrived) use for such
a setup:
class Modulo:
base = 256
def __init__(self,n):
self.val=int(n)
def __str__(self):
return str(self.val)
__repr__=__str__
def __hash__(self):
return self.val%self.base
def __eq__(self,other):
return hash(self)==hash(other)
def __iadd__(self,other):
try:
self.val+=other.val
except:
try:
self.val+=int(other)
except:
pass
return self
Two of these numbers will hash and compare equal if they are equal
modulo 'base'. Useful? Probably not. But it's plausibly defined.
ChrisA
--
http://mail.python.org/mailman/listinfo/python-list