Add a "key" parameter to bisect* functions?

Giacomo Alzetta giacomo.alzetta at gmail.com
Wed Sep 12 12:03:55 EDT 2012


Il giorno mercoledì 12 settembre 2012 17:54:31 UTC+2, Giacomo Alzetta ha scritto:
> I've just noticed that the bisect module lacks of the key parameter.
> 
> 
> 
> The documentation points to a recipe that could be used to handle a sorted collection, but I think it's an overkill if I want to bisect my sequence only once or twice with a key. Having something like `bisect(sequence, key=my_key)` would be much easier and would conform to the other operations such as max/min/sorted.
> 
> 
> 
> Is there some reason behind this lack?

Uhm, I've found this piece of documentation: http://docs.python.org/library/bisect.html#other-examples

Now, what it's stated there does not make sense for me:

1) Adding a key/reversed parameter wont decrease the speed of calls to bisect that does not use those parameters. At least a good implementation should guarantee that

2) Yes, providing a key means that either bisect should do some caching in order to speed multiple look-ups, or the keys have to be recomputed every time.
But, I think that using this as a reason to not provide this parameter is wrong.
It's up to the user to decide what has to be done to make code fast.
If he has to do multiple lookups then he should precompute them(but this is true also for sort etc.), but if he just has to use this feature once than computing "on-the-fly" is simply perfect.

3) Also, the fact that you can bisect only in asceding order sounds strange to me. It's not hard to bisect in both directions...

Probably it would be correct to document possible pitfalls of using the eventually added "key" and "reversed" parameters(such as multiple key evaluation etc.), but I can't see other cons to this.

Also, this change would be 100% backward compatible.



More information about the Python-list mailing list