Python 3.0, rich comparisons and sorting order

Carlos Ribeiro carribeiro at gmail.com
Tue Sep 21 14:25:38 EDT 2004


On Tue, 21 Sep 2004 17:42:35 +0000 (UTC), Steven Bethard
<steven.bethard at gmail.com> wrote:
> I'm not sure I follow your comparison here anyway, since you can't sort a
> dict...  Could you clarify?

Any hashable object can be used as a key. That's the point. If you're
using a balanced binary tree as a high performance object storage with
bounded search time (log N), then you're going to need comparisons to
work.

Anyway, the discussion so far gave me an idea: sortable objects could
implement the __key__ function to return a sortable value. Here it is:

1) comparison would work between a few types -- None, booleans,
numbers, and strings, in this order. It's an arbritrary but
determinist ordering, and does not deal with things such as complex
nmbers.

2) other objects would implement the __key__function for comparison.
__key__ would have to return one of the built-in, sortable types, as
described above.

This is a workable solution to preserve the current behavior (multiple
objects can be sorted). However, it has a disadvantage in that it's
not orthogonal -- but neither is restricting comparisons.

Just to make it clear, here it is how it works now:

>>> a = [ 3.5, -1.0, "", (0,1), None, "z"]
>>> a.sort()
>>> a
[None, -1.0, 3.5, '', 'z', (0, 1)]

None comes first, then numbers, then strings, then tuples. And sort
simply works. BTW, it even sorts tuples in a deterministic fashion --
is it going to be lost in Python 3.0 too?

Now that we're talking about tuples, another example:

>>> (0,1) < (1,0)
True
>>> (0,1) < [1,0]
False
>>> [0,1] < [1,0]
True

Lists come before sequences -- don't know if it does make sense, the
"correct" thing for sorting seems to consider then equal as far as
relative ordering is concerned; that would make (0,1) < [1,0] -> True.
But then, would it make (0,0) be the same as [0,0]? Of course not --
one is a list, the other one is a tuple. All this can be simply put
as:

a) Relative ordering (or partial ordering) is one thing;
b) Magnitude comparison is another thing, that sometimes coincide with
relative ordering;
c) Equality/inequality is yet another thing.

...and we're trying to solve all three with the same set of operators.
But please, don't try to propose anything more complex, it's not going
to help here :-)

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list