Rich Comparisons Gotcha

Luis Zarrabeitia kyrie at uh.cu
Sun Dec 7 15:23:46 CET 2008



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).
Well, sqrt is a function, and if its result value is defined as 4+4i, then the
answer is 'yes', otherwise, the answer should be no.

sqrt(4) is *not* -2, and should not be equal to -2. The standard definition of
the square root _function_ for real numbers is to take the non-negative real
root. I haven't heard of a standard square root _function_ for complex numbers
(there is of course, a definition of square root, but it is not a function).

So, if by your definition of sqrt, sqrt(32i) returns a number, there is no
ambiguity. -2 is not sqrt(4). If you need the answer to be 'True', you may be
asking the wrong question. 





More information about the Python-list mailing list