Skip to content

Commit 3c57ca6

Browse files
[3.8] bpo-39453: Fix contains method of list to hold strong references (GH-18204)
(cherry picked from commit f64abd1) Co-authored-by: Dong-hee Na <[email protected]>
1 parent 505b601 commit 3c57ca6

File tree

3 files changed

+16
-3
lines changed

3 files changed

+16
-3
lines changed

Lib/test/test_list.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,13 @@ def __eq__(self, other):
212212
with self.assertRaises(ValueError):
213213
lst.remove(lst)
214214

215+
# bpo-39453: list.__contains__ was not holding strong references
216+
# to list elements while calling PyObject_RichCompareBool().
217+
lst = [X(), X()]
218+
3 in lst
219+
lst = [X(), X()]
220+
X() in lst
221+
215222

216223
if __name__ == "__main__":
217224
unittest.main()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fixed a possible crash in :meth:`list.__contains__` when a list is changed
2+
during comparing items. Patch by Dong-hee Na.

Objects/listobject.c

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -397,12 +397,16 @@ list_length(PyListObject *a)
397397
static int
398398
list_contains(PyListObject *a, PyObject *el)
399399
{
400+
PyObject *item;
400401
Py_ssize_t i;
401402
int cmp;
402403

403-
for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
404-
cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
405-
Py_EQ);
404+
for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) {
405+
item = PyList_GET_ITEM(a, i);
406+
Py_INCREF(item);
407+
cmp = PyObject_RichCompareBool(el, item, Py_EQ);
408+
Py_DECREF(item);
409+
}
406410
return cmp;
407411
}
408412

0 commit comments

Comments
 (0)