[Python-ideas] Optional key to `bisect`'s functions?

Arnaud Delobelle arnodel at gmail.com
Thu Feb 9 15:27:20 CET 2012


On 9 February 2012 00:25, Guido van Rossum <guido at python.org> wrote:
> Basically Raymond says "bisect can call the key() function many times, which
> leads to bad design". His alternative, to use a list of (key, value) tuples,
> is often a bit clumsy when passing the sorted list to another function (e.g.
> for printing); having to transform the list using e.g. [v for (k, v) in a]
> feels clumsy and suboptimal.

Also, in Python 3 one can't assume that values will be comparable so
the (key, value) tuple trick won't work: comparing the tuples may well
throw a TypeError.  Here's a simple example below.  The class 'Person'
has no natural order, but we may want to keep a list of people sorted
by iq:

>>> class Person:
...     def __init__(self, height, iq):
...         self.height = height
...         self.iq = iq
...
>>> arno = Person(184, 101)
>>> guido = Person(179, 185)
>>> steve = Person(168, 101)
>>> key = lambda p: p.iq
>>> people = []
>>> bisect.insort(people, (key(arno), arno))
>>> bisect.insort(people, (key(guido), guido))
>>> bisect.insort(people, (key(steve), steve))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: Person() < Person()
>>>

-- 
Arnaud



More information about the Python-ideas mailing list