-
-
Notifications
You must be signed in to change notification settings - Fork 32.4k
Closed
Labels
docsDocumentation in the Doc dirDocumentation in the Doc dirstdlibPython modules in the Lib dirPython modules in the Lib dir
Description
The key functions generated by the functools.cmp_to_key function don't work with bisect.bisect_right or bisect.bisect_left, raising a TypeError with the message "TypeError: other argument must be K instance" when used.
Consider the following example derived from the Sorting HOWTO page (https://docs.python.org/3/howto/sorting.html#the-old-way-using-the-cmp-parameter)
Python 3.10.4 (main, Apr 25 2022, 16:19:06) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from functools import cmp_to_key
>>> from bisect import bisect_right, bisect_left
>>> ns=[1,2,3,4,5]
>>> def numeric_compare(x, y):
... return x - y
...
>>> bisect_right(ns, 2, key=cmp_to_key(numeric_compare))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: other argument must be K instance
>>> bisect_left(ns, 2, key=cmp_to_key(numeric_compare))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: other argument must be K instance
The methods bisect.insort_left and bisect.insort_right functions do seem work correctly with these key functions:
Python 3.10.4 (main, Apr 25 2022, 16:19:06) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from bisect import insort_right, insort_left
>>> from functools import cmp_to_key
>>> def numeric_compare(x, y):
... return x - y
...
>>> ns=[1, 2, 3, 4, 5]
>>> insort_right(ns, 2, key=cmp_to_key(numeric_compare))
>>> ns
[1, 2, 2, 3, 4, 5]
Your environment
- Python version 3.10.4
- Linux x86
Metadata
Metadata
Assignees
Labels
docsDocumentation in the Doc dirDocumentation in the Doc dirstdlibPython modules in the Lib dirPython modules in the Lib dir