# When is min(a, b) != min(b, a)?

Robert Kern robert.kern at gmail.com
Fri Jan 25 19:50:53 CET 2008

```Marc 'BlackJack' Rintsch wrote:
> On Fri, 25 Jan 2008 07:57:38 +0000, Pete Forman wrote:
>
>> Mark Dickinson <dickinsm at gmail.com> writes:
>>
>>  > Any change to Python that made == and != checks involving NaNs raise
>>  > an exception would have to consider the consequences for set, dict,
>>  > list membership testing.
>>  > […]
>>  > and if Python had separate operators for these two purposes it
>>  > wouldn't be Python any more.
>>
>> There are separate Python operators, "==" and "is".
>
> So what?  ``==`` is used for both ``==`` and set/dict/list membership
> testing and "nested comparison" of those structures.  There is no ``is``
> involved.

Sure, there is. ``is`` is checked before ``==``. But that's just an optimization
for the usual case where "x is x" implies "x == x", to bring this full circle,
something that is not true for NaNs.

In [48]: class A(object):
def __init__(self, x):
self.x = x
def __eq__(self, other):
print '%r.__eq__(%r)' % (self, other)
return self.x == other.x
def __ne__(self, other):
return not (self == other)
def __hash__(self):
print '%r.__hash__()' % (self,)
return hash(self.x)
def __repr__(self):
return 'A(%r)' % (self.x,)
....:
....:

In [61]: a = A(1)

In [62]: b = A(2)

In [63]: c = A(1)

In [64]: a is c
Out[64]: False

In [65]: a == c
A(1).__eq__(A(1))
Out[65]: True

In [66]: a == b
A(1).__eq__(A(2))
Out[66]: False

In [67]: L = [a, b, c]

In [68]: a in L
Out[68]: True

In [69]: b in L
A(2).__eq__(A(1))
Out[69]: True

In [70]: c in L
A(1).__eq__(A(1))
Out[70]: True

In [71]: S = set([a, b, c])
A(1).__hash__()
A(2).__hash__()
A(1).__hash__()
A(1).__eq__(A(1))

In [72]: a in S
A(1).__hash__()
Out[72]: True

In [73]: b in S
A(2).__hash__()
Out[73]: True

In [74]: c in S
A(1).__hash__()
A(1).__eq__(A(1))
Out[74]: True

In [75]: D = {a: 1, b: 2, c: 1}
A(1).__hash__()
A(2).__hash__()
A(1).__hash__()
A(1).__eq__(A(1))

In [76]: D
Out[76]: A(2).__eq__(A(1))
{A(1): 1, A(2): 2}

In [77]: a in D
A(1).__hash__()
Out[77]: True

In [78]: b in D
A(2).__hash__()
Out[78]: True

In [79]: c in D
A(1).__hash__()
A(1).__eq__(A(1))
Out[79]: True

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma