Python 3.0, rich comparisons and sorting order

David Bolen db3l at fitlinxx.com
Wed Sep 22 01:56:19 EDT 2004


"Delaney, Timothy C (Timothy)" <tdelaney at avaya.com> writes:

> Carlos Ribeiro wrote:
> 
> > 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)]
> 
> Add a complex to that list and watch the result.

Or any user defined type that performs operations in the comparison
functions that might end up raising an exception or rejecting some
comparisons.

> Not all lists are sortable *now*. The change in Python 3.0 is to make it
> much more obvious that you *can't* just sort a list of unknown types.

While I used to treat the "sort heterogeneous lists" as an attractive
quality of the inter-type comparisons, I've pretty much come around to
thinking that it's not worth it, particular since as you say, with
rich comparisons you can't guarantee such behavior any more anyway.

But what really emphasized it for me is having seen multiple new
Python programmers get burned by Python silently comparing strings to
numbers (where they forgot to convert user input as a string into a
numeric type), but not in the way they expect, which can be a subtle
failure.  I think an exception in such cases is actually more Pythonic
since it always feels like a mini-wart when I explain it to them.
I've wondered if the legality of inter-type comparisons was really a
design intention, or more a consequence of the inability of the
earlier interpreter versions to have exceptions raised during the
comparison process.

-- David



More information about the Python-list mailing list