Python 3.0, rich comparisons and sorting order

Alex Martelli aleaxit at yahoo.com
Wed Sep 22 05:03:51 EDT 2004


Steven Bethard <steven.bethard at gmail.com> wrote:
   ...
> BTree).  If __cmp__ starts raising TypeErrors, your code could do something
> like:
> 
> def insert(self, val):
>     try:
>         c = cmp(self.val, val)
>     except TypeError:
>         c = -1 # self.val and val were not of the same type
>                # make some arbitrary decision here
>     ... # insert according to cmp result

Nope, this would probably lead to subtle and hard to debug errors, since
both a<b and b<a would appear to be true for some heterogeneous values
of a and b, violating a crucial semantic constraint of the < operator.

The fact that some such problems were observed in Python itself was used
as an argument to justify not doing comparisons among het types in
Python; I argue that pushing such subtle responsibilities down to Python
_users_ is no progress.

An acceptable compromise might be to have a universal_compare function
available in some module, already carefully coded to avoid the subtle
traps.  I believe a universal_lt might in fact suffice, and that it
would only need to ensure <'s semantic constraints (specifically their
connection with ==) on types where == "does nothing tricky"... all
built-in types, but only _some_ user-coded types, namely the sensible
ones.  If one codes an __eq__ which randomly returns True or False, for
example, there is no way universal_whatever can sensibly cooperate with
it to ensure (e.g.) that a==b implies not a<b and not b<a and VV!-)


Alex



More information about the Python-list mailing list