[Python-Dev] Tuples and underorderable types

Daniel Diniz ajaksu at gmail.com
Fri Apr 24 20:53:41 CEST 2009

Raymond Hettinger wrote:
> The problem is that a basic python pattern is now broken
> in a way that may not readily surface during testing.
> I'm wondering if there is something we can do to mitigate
> the issue in a general way.  It bites that the venerable technique
> of tuple sorting has lost some of its mojo.  This may be
> an unintended consequence of eliminating default comparisons.

There could be a high performance, non-lame version of the mapping
pattern below available in the stdlib (or at least in the docs):

keymap = {type(lambda: 1) : id}

def decorate_helper(tup):
    return tuple(keymap[type(i)](i) if type(i) in keymap else i for i in tup)

tasks = [(10, lambda: 0), (20, lambda: 1), (10, lambda: 2)]

This works when comparing different types too, but then some care must
be taken to avoid bad surprises:

keymap[type(1j)] = abs
imaginary_tasks = [(10j, lambda: 0), (20, lambda: 1), (10+1j, lambda: 2)]
imaginary_tasks.sort(key=decorate_helper) # not so bad if intended

mixed_tasks = [(lambda: 0,), (0.0,), (2**32,)]
mixed_tasks.sort(key=decorate_helper) # oops, not the same order as in 2.x


More information about the Python-Dev mailing list