Would there be support for a more general cmp/__cmp__

Christopher Subich csubich.spam.block at spam.subich.block.com
Wed Oct 26 09:20:22 EDT 2005


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 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.

>>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.

A change that cmp throw an exception iff the two objects, rather than 
the two classes, were incomparable (allowing comparisons of( 1+0j and 
2+0j) and ({a} and {a,b}) but not (1+1j and 2+0j) and ({a} and {b})) is 
a stylistic guideline, since it's already possible to write your own 
classes this way.  The only place this change would matter is in the 
standard library code, and in just a few places at that.



More information about the Python-list mailing list