[Python-3000] Please re-add __cmp__ to python 3000
Greg Ewing
greg.ewing at canterbury.ac.nz
Wed Oct 31 06:13:36 CET 2007
Adam Olsen wrote:
> for a, b in zip(self.data, other.data):
> result = richcmp(a, b, ordered)
> if result:
> return result
That can't be right, because there are *three* possible
results you need to be able to distinguish from comparing
a pair of elements: "stop and return True", "stop and
return False", and "keep going". There's no way you can
get that out of a boolean return value.
Maybe what we need to do is enhance __cmp__ so that
it has *four* possible return values: -1, 0, 1 and
UnequalButNotOrdered.
The scheme for handling a comparison 'op' between
two values 'a' and 'b' would then be:
1) Try a.__richcmp__(op, b) and vice versa. If either
of these produces a result, return it.
2) Try a.__cmp__(b) and vice versa. If either of these
produces a result, then
a) If the result is -1, 0 or 1, return an appropriate
value based on the operation.
b) If the result is UnequalButNotOrdered, and the
operation is == or !=, return an appropriate
value.
c) Otherwise, raise an exception.
The pattern for comparing sequences would become:
def __cmp__(self, other):
for a, b in zip(self.items, other.items):
result = cmp(a, b)
if result != 0:
return result
return 0
Which is actually the same as it is now, with an added
bit of It Just Works behaviour: if any of the element
comparisons gives UnequalButNotOrdered, then the whole
sequence gets reported as such.
--
Greg
More information about the Python-3000
mailing list