Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Lib/bisect.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def bisect_right(a, x, lo=0, hi=None, *, key=None):

if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
if hi is None or hi < 0:
hi = len(a)
# Note, the comparison uses "<" to match the
# __lt__() logic in list.sort() and in heapq.
Expand Down Expand Up @@ -86,7 +86,7 @@ def bisect_left(a, x, lo=0, hi=None, *, key=None):

if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
if hi is None or hi < 0:
hi = len(a)
# Note, the comparison uses "<" to match the
# __lt__() logic in list.sort() and in heapq.
Expand Down
7 changes: 6 additions & 1 deletion Lib/test/test_bisect.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,13 +118,18 @@ def test_precomputed(self):
self.assertEqual(func(data, elem), expected)
self.assertEqual(func(UserList(data), elem), expected)

def test_negative_lo(self):
def test_negative_hi_lo(self):
# Issue 3301
mod = self.module
self.assertRaises(ValueError, mod.bisect_left, [1, 2, 3], 5, -1, 3)
self.assertRaises(ValueError, mod.bisect_right, [1, 2, 3], 5, -1, 3)
self.assertRaises(ValueError, mod.insort_left, [1, 2, 3], 5, -1, 3)
self.assertRaises(ValueError, mod.insort_right, [1, 2, 3], 5, -1, 3)
# Test c implementation
self.assertRaises(ValueError, c_bisect.bisect_left, [1, 2, 3], 5, 3, -2)
self.assertRaises(ValueError, c_bisect.bisect_right, [1, 2, 3], 5, 3, -2)
self.assertRaises(ValueError, c_bisect.insort_left, [1, 2, 3], 5, 3, -2)
self.assertRaises(ValueError, c_bisect.insort_right, [1, 2, 3], 5, 3, -2)

def test_large_range(self):
# Issue 13496
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Allow negative values ​​for ``hi`` argument of ``bisect_left/right`` and ``insort_left/right``.
8 changes: 8 additions & 0 deletions Modules/_bisectmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ internal_bisect_right(PyObject *list, PyObject *item, Py_ssize_t lo, Py_ssize_t
if (hi < 0)
return -1;
}
if (hi < 0) {
PyErr_SetString(PyExc_ValueError, "hi must be non-negative");
return -1;
}
ssizeargfunc sq_item = get_sq_item(list);
if (sq_item == NULL) {
return -1;
Expand Down Expand Up @@ -250,6 +254,10 @@ internal_bisect_left(PyObject *list, PyObject *item, Py_ssize_t lo, Py_ssize_t h
if (hi < 0)
return -1;
}
if (hi < 0) {
PyErr_SetString(PyExc_ValueError, "hi must be non-negative");
return -1;
}
ssizeargfunc sq_item = get_sq_item(list);
if (sq_item == NULL) {
return -1;
Expand Down
Loading