Would there be support for a more general cmp/__cmp__

Toby Dickenson tdickenson at devmail.geminidataloggers.co.uk
Thu Oct 20 13:24:30 CEST 2005

On Thursday 20 October 2005 11:53, Steve Holden wrote:

> Personally I'm still not convinced that your requirement reflects a 
> substantial use case (but then I'm getting used to that ;-). Just 
> because an ordering is partial that doesn't mean that two instances of a 
> class shouldn't be compared.

C++ has a cmp template function which can be implemented to define a total 
ordering for one type. This can be reliably used by implementations of 
ordered tree containers (for example) so that this container template class 
can only be instantiated for holding types that provide this comparison 
template function.

One disadvantage is that these template container classes can only hold one 

ZODB's BTrees work in a similar way but use the regular python comparison 
function, and the lack of a guarantee of a total ordering can be a liability.
Described here in 2002, but I think same is true today:

A BTree might contain two objects that are incomparable. That is, they raise 
an exception when compared. However the user will not know this if by 
coincidence the BTree implementation has never needed to compare these two 

Now removing a third object from the container such that these two 
incomparable objects are adjacent in the BTree. There is a possibility that 
an exception might be raised when *reading* content from the BTree, since the 
BTree implementation now might need to compare this pair of objects.

> What would you have Python do when the programmer tries to perform an 
> invalid comparison (i.e. what are the exact semantics imposed when 
> __cmp__() returns None/raises an exception)?

Its too late to handle this by the time a specific comparison method of an 
individual object is being called. If you need a total ordering across a 
domain of objects then you need to involve some representation of that domain 
as a whole. 

Toby Dickenson

More information about the Python-list mailing list