Rich Comparisons Gotcha

James Stroud jstroud at mbi.ucla.edu
Sun Dec 7 16:53:51 EST 2008


Luis Zarrabeitia wrote:
> 
> Quoting James Stroud <jstroud at mbi.ucla.edu>:
> 
>> First, here is why the ability to throw an error is a feature:
>>
>> class Apple(object):
>>    def __init__(self, appleness):
>>      self.appleness = appleness
>>    def __cmp__(self, other):
>>      assert isinstance(other, Apple), 'must compare apples to apples'
>>      return cmp(self.appleness, other.appleness)
>>
>> class Orange(object): pass
>>
>> Apple(42) == Orange()
> 
> I beg to disagree.
> The right answer for the question "Am I equal to this chair right here?" is not
> "I don't know", nor "I can't compare". The answer is "No, I'm not a chair, thus
> I'm not equal to this chair right here". If someone comes to my house, looking
> for me, he will not run away because he sees a chair before he sees me. Your
> assert doesn't belong inside the methot, it should be up to the caller to decide
> if the human-chair comparisons make sense or not. I certainly don't want to be
> type-checking when looking for an object within a mixed-type collection. 
> 
>> This reminds me of complex numbers: would 4 + 4i be equal to sqrt(32)? 
> 
> I assume you meant sqrt(32i).

No, I definitely didn't mean sqrt(32i). I'm using sqrt() to represent 
the mathematical square root, and not an arbitrary function one might 
define, by the way.

My point is that 4 + 4i, sqrt(32), and sqrt(-32) all exist in different 
spaces. They are not comparable, even when testing for equality in a 
pure mathematical sense. If when encounter these values in our programs, 
we might like the power to decide the results of these comparisons. In 
one context it might make sense to throw an exception, in another, it 
might make sense to return False based on the fact that we consider them 
different "types", in yet another context, it might make sense to look 
at complex plane values as vectors and return their scalar magnitude for 
comparison to real numbers. I think this ability to define the results 
of comparisons is not a shortcoming of the language but a strength.

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com



More information about the Python-list mailing list