cmp and sorting non-symmetric types

Carl Banks pavlovevidence at
Tue Nov 13 22:18:23 CET 2007

On Nov 13, 1:51 pm, "Adam Olsen" <rha... at> wrote:
> (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.

I second Raymond Hettinger's strong -1 on this.

I would further suggest that it's the wrong solution even insofar as
it's a problem.  The right solution is to use comparison operators
only for ordered comparisons, not for subset and superset testing.
Unfortunately, the rogue operators are already there and in use, so
the right solution would probably cause more trouble than it would
save at this point.  But it'd still cause less trouble than
resurrecting the __cmp__ operator.

Carl Banks

More information about the Python-list mailing list