Rich Comparisons Gotcha

Robert Kern robert.kern at gmail.com
Tue Dec 9 00:01:50 CET 2008


MRAB wrote:
> Terry Reedy wrote:
>> Rasmus Fogh wrote:
>>
>>> For my personal problem I could indeed wrap all objects in a wrapper 
>>> with
>>> whatever 'correct' behaviour I want (thanks, TJR). It does seem a bit
>>
>> I was not suggesting that you wrap *everything*, merely an adaptor for 
>> numpy arrays in whatever subclass and source it is that feeds them to 
>> your code.  It is fairly unusual, I think, to find numpy arrays 'in 
>> the wild', outside the constrained context of numerical code where the 
>> programmer uses them intentionally and hopefully understands their 
>> peculiarities.
>>
>>> much, though, just to get code like this to work as intended:
>>>   alist.append(x)
>>>   print ('x is present: ', x in alist)
>>
>> Even if rich comparisons as you propose, the above would *still* not 
>> necessarily work.  Collection classes can define a __contains__ that 
>> overrides the default and that can do anything, though True/False is 
>> recommended.
>>
> If you have a list of results and you want to see whether one of them is 
> Nan then the obvious way is "Nan in results", but __contains__ uses 
> __eq__ and Nan == Nan returns False, so "Nan in results" returns False. 
> Hmm... "Nan is Nan" returns True,

However, "Nan is SomeOtherNan" does not return True.

> so if there was a version of 
> __contains__ which used "is" then "Nan in results" would return True. 
> Perhaps "Nan is in results"? Or would that be too confusing, ie "in" vs 
> "is in"?

list.__contains__() already checks with "is" before it tries "==".


In [65]: from numpy import nan, inf

In [66]: other_nan = inf/inf

In [67]: nan in [nan]
Out[67]: True

In [68]: nan in [other_nan]
Out[68]: False


-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list