[Python-Dev] Re: Re: lists v. tuples

Guido van Rossum guido@python.org
Sun, 16 Mar 2003 15:34:17 -0500


> Guido> I realized the first sentence wasn't very clear.  I meant that
> Guido> implementing cmp() is inefficient without __cmp__ for some types
> Guido> (especially container types).  Example:
> 
> Guido>  cmp(range(1000)+[1], range(1000)+[0])
> 
> Guido> If the list type implements __cmp__, each of the pairs of items
> Guido> is compared once.  OTOH, if the list type only implemented
> Guido> __lt__, __eq__ and __gt__, cmp() presumably would have to try
> Guido> one of those first, and then another one.  If it picked __lt__
> Guido> followed by __eq__, it would get two False results in a row,
> Guido> meaning it could return 1 (cmp() doesn't really expect
> Guido> incomparable results :-), but at the cost of comparing each
> Guido> pair of items twice.  If cmp() picked another set of two
> Guido> operators to try, I'd simply adjust the example.

[Andrew Koenig]
> Yes.  If you want to present a 3-way comparison to users, an
> underlying 3-way comparison is the fastest way to do it.  The trouble
> is that a 3-way comparison is definitely not the fastest way to
> present a 2-way comparison to users.
> 
> So if you want users to see separate 2-way and 3-way comparisons,
> I think the fastest way to implement them is not to try to force
> commonality where none exists.

This seems an argument for keeping both __cmp__ and the six __lt__
etc.  Yet TOOWTDI makes me want to get rid of __cmp__.

I wonder, what's the need for cmp()?  My hunch is that the main reason
for cmp() is that it's specified in various APIs -- e.g. list.sort(),
or FP hardware.  But don't those APIs usually specify cmp() because
their designers (mistakenly) believed the three different outcomes
were easy to compute together and it would simplify the API?

--Guido van Rossum (home page: http://www.python.org/~guido/)