Would there be support for a more general cmp/__cmp__

Antoon Pardon apardon at forel.vub.ac.be
Thu Oct 27 04:27:53 EDT 2005


Op 2005-10-26, Christopher Subich schreef <csubich.spam.block at spam.subich.block.com>:
> Antoon Pardon wrote:
>> Op 2005-10-25, Christopher Subich schreef <csubich.spam.block at spam.subich.block.com>:
>>>
>>>My biggest complaint here is about returning None or IncomparableValue; 
>>>if that happens, then all code that relies on cmp returning a numeric 
>>>result will have to be rewritten.
>> 
>> 
>> I don't know. There are two possibilities.
>> 
>> 1) The user is working with a total order. In that case the None
>> or IncomparableValues won't be returned anyway so nothing about
>> his code has to change.
>> 
>> 2) The user is working with a partial order. In that case cmp
>> doesn't provide consistent results so the use of cmp in this
>> case was a bug anyway.
>
> Case 3) The user is working with an unknown class, using duck typing, 
> and expects a total order.  If cmp suddenly returned Incomparable or 
> None, the code would break in Unexpected Ways, with Undefined Behavior.

This is case 2. Under the current circumstances working with cmp with
a partial order will give inconsistent behaviour. So your code is
already broken for relying on cmp to give consistent results in 
circumstances it can't.

> This is a classic "exception versus error code" argument; in this case, 
> returning None would be the error flag.  It's almost always better to 
> just throw the exception, because then this allows error-checking at a 
> more natural level.

If you prefer a raised exception, I could live with that.

>>>As for saying that cmp should return some times and raise an exception 
>>>other times, I just find it squicky.
>> 
>> 
>> But cmp already behaves this way. The only difference would be that
>> the decision would be made based on the values of the objects instead
>> of only their class.
>> 
>> 
>>>Admittedly, this is entirely up to 
>>>the class designer, and your proposed guideline wouldn't change cmp's 
>>>behavior for clases that /are/ totally ordered.
>>>
>>>Then again, sets excepted, your guideline doesn't seem very applicable 
>>>in standard library code.
>> 
>> 
>> Well AFAIAC this isn't specific about library code.
>
> A change that cmp return a 4th possible "value" (None or Incomparable) 
> is a fundamental language change.  Because this would break large 
> amounts of existing code, it's a bad idea.

I have always included the option that cmp would raise an exception
instead of returning a fourth value.

-- 
Antoon Pardon



More information about the Python-list mailing list