Skip to content

Commit 0774692

Browse files
refactor: hoist the comparison logic
1 parent 8447fa6 commit 0774692

File tree

1 file changed

+22
-33
lines changed

1 file changed

+22
-33
lines changed

Objects/listobject.c

Lines changed: 22 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3433,16 +3433,12 @@ list_richcompare_impl(PyObject *v, PyObject *w, int op)
34333433
}
34343434

34353435
/* Search for the first index where items are different.
3436-
* Keep vitem/witem alive across the break so that the final ordering
3437-
* comparison uses the same differing objects.
3438-
* This is required as PyObject_RichCompareBool may release the GIL and
3439-
* the list may be mutated in the meantime.
3436+
* We incref vitem/witem before calling PyObject_RichCompareBool, which may
3437+
* release the GIL and allow the list to be mutated in the meantime.
34403438
*/
3441-
PyObject *vitem = NULL;
3442-
PyObject *witem = NULL;
34433439
for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
3444-
vitem = vl->ob_item[i];
3445-
witem = wl->ob_item[i];
3440+
PyObject *vitem = vl->ob_item[i];
3441+
PyObject *witem = wl->ob_item[i];
34463442
if (vitem == witem) {
34473443
continue;
34483444
}
@@ -3456,37 +3452,30 @@ list_richcompare_impl(PyObject *v, PyObject *w, int op)
34563452
return NULL;
34573453
}
34583454
if (!k) {
3459-
/* keep vitem/witem alive for the final comparison */
3460-
break;
3455+
/* We have a differing item -- shortcuts for EQ/NE */
3456+
if (op == Py_EQ) {
3457+
Py_DECREF(vitem);
3458+
Py_DECREF(witem);
3459+
Py_RETURN_FALSE;
3460+
}
3461+
if (op == Py_NE) {
3462+
Py_DECREF(vitem);
3463+
Py_DECREF(witem);
3464+
Py_RETURN_TRUE;
3465+
}
3466+
/* Compare the differing items using the proper operator */
3467+
PyObject *result = PyObject_RichCompare(vitem, witem, op);
3468+
Py_DECREF(vitem);
3469+
Py_DECREF(witem);
3470+
return result;
34613471
}
34623472

34633473
Py_DECREF(vitem);
34643474
Py_DECREF(witem);
3465-
vitem = witem = NULL;
3466-
}
3467-
3468-
if (vitem == NULL) {
3469-
/* All compared elements were equal -- compare sizes */
3470-
Py_RETURN_RICHCOMPARE(Py_SIZE(vl), Py_SIZE(wl), op);
34713475
}
34723476

3473-
/* We have an item that differs -- shortcuts for EQ/NE */
3474-
if (op == Py_EQ) {
3475-
Py_DECREF(vitem);
3476-
Py_DECREF(witem);
3477-
Py_RETURN_FALSE;
3478-
}
3479-
if (op == Py_NE) {
3480-
Py_DECREF(vitem);
3481-
Py_DECREF(witem);
3482-
Py_RETURN_TRUE;
3483-
}
3484-
3485-
/* Compare the differing items using the proper operator */
3486-
PyObject *result = PyObject_RichCompare(vitem, witem, op);
3487-
Py_DECREF(vitem);
3488-
Py_DECREF(witem);
3489-
return result;
3477+
/* All compared elements were equal -- compare sizes */
3478+
Py_RETURN_RICHCOMPARE(Py_SIZE(vl), Py_SIZE(wl), op);
34903479
}
34913480

34923481
static PyObject *

0 commit comments

Comments
 (0)