[Python-Dev] PEP 218 (sets); moving set.py to Lib

Guido van Rossum guido@python.org
Sat, 17 Aug 2002 16:10:57 -0400


> How about sorting with this comparison function:
> 
> errors = (TypeError, ...?)
> 
> def cmpval(x):
>     try:
>         cmp(0, x)
>     except errors:
>         try:
>             h = hash(x)
>         except errors:
>             h = -1
>         return (1, h, id(x))
>     return (0, x)
> 
> 
> def robust_cmp(a,b):
>     try:
>         return cmp(a,b)
>     except errors:
>         try:
>             return cmp(cmpval(a), cmpval(b))
>         except errors:
>             return 0
> 
> >>> l=[3j, 2j, 4, 4j, 1, 2, 1j, 3]
> >>> l.sort(robust_cmp)
> >>> l
> [1, 2, 3, 4, 1j, 2j, 3j, 4j]
> 
> It's equivalent to standard cmp if no errors are encountered. For lists
> containing uncomparable objects it produces a pretty consistent order.
> It's not perfect but should be good enough for aesthetic purposes.

Too convoluted.  Explicit is better than implicit.

--Guido van Rossum (home page: http://www.python.org/~guido/)