Python 3.0, rich comparisons and sorting order
Andrew Dalke
adalke at mindspring.com
Tue Sep 21 16:54:25 EDT 2004
Carlos Ribeiro wrote:
> I know it, and that's exactly my question -- if this is going to be
> the way to do it in Python 3000. Today (2.4) there are FOUR ways to
> make it work: passing a compare function as an argument to sort(),
> passing a key funciton as an argument to sort(), implementing a
> __cmp__ function, or implementing the rich comparison methods. If the
> main goal of Py3K is to have only one obvious way to do it, what one
> is it going to be? I think that the best way should be the simplest
> one: make sort() work whatever is passed to it in a reasonably way,
> and decide to have one preferred way to extend its behavior.
Get rid of __cmp__.
Then there will be:
one native way to compare two objects to each other,
one way to override how to compare two objects
one way to do a Schwartzian transform
And regarding the last, "practicality beats purity."
> Now that's a harder question :-) Any ordering for multiple types is
> going to be arbitrary -- but it still may be considered reasonable if
> it reflects our common sense when it comes to ordering. In some cases,
> it's still a matter of choice, but once decided, it's deterministic,
> and that's what it takes for sorting.
So long as you allow user-defined comparisons then there's
no guarantee that it's consistent, much less deterministic.
I can define __cmp__ to do whatever I want.
>>> class Strange:
... def __cmp__(self, other):
... if isinstance(other, float): return -1
... else: return 1
...
>>> x = Strange()
>>> 10 < x < 5.0
True
>>>
or for something non-deterministic
class WaitCompare:
def __init__(self, val): self.val = val
def __cmp__(self, other):
while 1:
page = urllib.urlopen("http://whitehouse.gov/").read()
if page.find(self.val):
break
return cmp(self.val, other)
L = [WaitCompare("Andrew Dalke"),
WaitCompare("America's New Communist Leaders"),
WaitCompare("Life discovered on Mercury")]
L.sort()
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list