Python 3.0, rich comparisons and sorting order

Andrew Dalke adalke at mindspring.com
Tue Sep 21 22:34:03 CEST 2004


Steven Bethard wrote:
> Presumably you could change how sort works so that it first stratifies
> the list by type, and then sorts for each type.  The types would then
> be ordered arbitrarily (perhaps by the id of their type?)...  Might
> slow down the normal-case sort though...

You've just about explained what Python does with the
types themselves cannot be compared.

It took a lot of work to get mostly correct.  Consider
an old bug which was seen when doing

     5 < [4]
   [4] < 3L
    3L < 4

Is 5 < [4]?  They can't be compared directly so Python
used to compare type names.  Is "int" < "list"?  Yes.

Is [4] < 3L?  Those instances can't be compared but the
type names can, so that is "list" < "long"?  Yes.

Is 3L < 4?  Yes, because those two *can* be compared
directly.

Therefore I've just shown that 5 < 4.  Any sort that
falls back to comparisons based on type will have this
problem because the sort ordering defined on instances
does not need to agree with the ordering defined on
types.

As I recall, Python "fixed" it by using "" as the type
name when doing a comparison that involves a numeric.
It's still a hack and there are ways to get around it.


> Yeah, by restricting comparisons, we'd be basically saying that sort
> is only defined for lists that take the form list<some_type>.

or where a compare function can be passed to .sort(), or
where (in 2.4) a keys function can be passed to get the
objects used for the comparison.  Why is this a problem?

Python's philosophy includes
   "In the face of ambiguity, refuse the temptation to guess."

If you want sort to guess, tell it how to guess.


				Andrew
				dalke at dalkescientific.com



More information about the Python-list mailing list