cmp and sorting non-symmetric types

Adam Olsen rhamph at
Tue Nov 13 19:51:59 CET 2007

(I've had trouble getting response for collaboration on a PEP.
Perhaps I'm the only interested party?)

Although py3k raises an exception for completely unsortable types, it
continues to silently do the wrong thing for non-symmetric types that
overload comparison operator with special meanings.

>>> a = set([1])
>>> b = set([2, 5])
>>> c = set([1, 2])
>>> sorted([a, c, b])
[{1}, {1, 2}, {2, 5}]
>>> sorted([a, b, c])
[{1}, {2, 5}, {1, 2}]

To solve this I propose a revived cmp (as per the previous thread[1]),
which is the preferred path for orderings.  The rich comparison
operators will be simple wrappers for cmp() (ensuring an exception is
raised if they're not merely comparing for equality.)

Thus, set would need 7 methods defined (6 rich comparisons plus
__cmp__, although it could skip __eq__ and __ne__), whereas nearly all
other types (int, list, etc) need only __cmp__.

Code which uses <= to compare sets would be assumed to want subset
operations.  Generic containers should use cmp() exclusively.


Adam Olsen, aka Rhamphoryncus

More information about the Python-list mailing list