From bc8288b4d75759310e2e50e47a7da214ddd3c260 Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Mon, 30 Nov 2026 23:49:40 +0100 Subject: [PATCH] gh-162894: No longer shrink the list in PyList_Extend() PyList_Append(), PyList_Extend() and PyList_Insert() can no longer shrink the list. It avoids shrinking a list created by PyList_New(n) followed by Py_SET_SIZE(list, 0) to preallocate 'n' items. Changes: * Add list_resize_shrink() * Add test_shrink() to test_capi.test_list * Add _testcapi.LIST_SMALL_ALLOCATED * Add _testcapi.list_get_allocated() --- Include/internal/pycore_list.h | 2 + Lib/test/test_capi/test_list.py | 80 +++++++++++++++++++ ...-12-01-00-21-31.gh-issue-162894.U_2TCv.rst | 4 + Modules/_testcapi/list.c | 23 +++++- Objects/listobject.c | 57 +++++++++---- 5 files changed, 150 insertions(+), 16 deletions(-) create mode 100644 Misc/NEWS.d/next/C_API/2026-12-01-00-21-31.gh-issue-162894.U_2TCv.rst diff --git a/Include/internal/pycore_list.h b/Include/internal/pycore_list.h index df0d00f752573b..6db69da20c9eaf 100644 --- a/Include/internal/pycore_list.h +++ b/Include/internal/pycore_list.h @@ -12,6 +12,8 @@ extern "C" { #include "pycore_stackref.h" #endif +#define _Py_LIST_SMALL_ALLOCATED 32 + PyAPI_FUNC(PyObject*) _PyList_Extend(PyListObject *, PyObject *); PyAPI_FUNC(PyObject) *_PyList_SliceSubscript(PyObject*, PyObject*); PyAPI_FUNC(PyObject *) _PyList_BinarySlice(PyObject *, PyObject *, PyObject *); diff --git a/Lib/test/test_capi/test_list.py b/Lib/test/test_capi/test_list.py index 05cc36b993b1ad..c42ac075dd9c87 100644 --- a/Lib/test/test_capi/test_list.py +++ b/Lib/test/test_capi/test_list.py @@ -358,6 +358,86 @@ def test_uninitialized_list_repr(self): lst = _testlimitedcapi.list_new(3) self.assertEqual(repr(lst), '[, , ]') + def test_shrink(self): + # Check list methods shrinking the list: methods calling + # list_resize_shrink(). + get_allocated = _testcapi.list_get_allocated + LIST_SMALL_ALLOCATED = _testcapi.LIST_SMALL_ALLOCATED + + def check_allocated(lst, expected_length): + size = len(lst) + self.assertEqual(size, expected_length) + + # See py_list_resize() in Objects/listobject.c + expected = max(size + (size >> 1) + 6, LIST_SMALL_ALLOCATED) + self.assertLessEqual(get_allocated(lst), expected) + + # del list[start:end] + lst = list(range(1024)) + self.assertGreaterEqual(get_allocated(lst), 1024) + del lst[128:] + check_allocated(lst, 128) + del lst[8:] + check_allocated(lst, 8) + + # del list[start:end:step] with step != 1 + lst = list(range(1024)) + self.assertGreaterEqual(get_allocated(lst), 1024) + del lst[::2] + del lst[::2] + check_allocated(lst, 256) + del lst[::2] + del lst[::2] + del lst[::2] + del lst[::2] + check_allocated(lst, 16) + + # del list[index] + lst = list(range(1024)) + self.assertGreaterEqual(get_allocated(lst), 1024) + for _ in range(1024 - 128): + del lst[-1] + check_allocated(lst, 128) + for _ in range(120): + del lst[-1] + check_allocated(lst, 8) + + # list.pop() + lst = list(range(1024)) + self.assertGreaterEqual(get_allocated(lst), 1024) + for _ in range(1024 - 128): + lst.pop() + check_allocated(lst, 128) + for _ in range(120): + lst.pop() + check_allocated(lst, 8) + + # Iterator with a bad __length_hint__() estimation + class Iterator: + def __init__(self, items): + self.data = tuple(items) + self.pos = 0 + + def __iter__(self): + return self + + def __length_hint__(self): + return len(self.data) * 8 + + def __next__(self): + try: + item = self.data[self.pos] + except IndexError: + raise StopIteration + self.pos += 1 + return item + + # list.extend(iterator) with bad __length_hint__() estimation + lst = [] + items = list(range(8)) + lst.extend(Iterator(items)) + check_allocated(lst, len(items)) + if __name__ == "__main__": unittest.main() diff --git a/Misc/NEWS.d/next/C_API/2026-12-01-00-21-31.gh-issue-162894.U_2TCv.rst b/Misc/NEWS.d/next/C_API/2026-12-01-00-21-31.gh-issue-162894.U_2TCv.rst new file mode 100644 index 00000000000000..932e887a6ef046 --- /dev/null +++ b/Misc/NEWS.d/next/C_API/2026-12-01-00-21-31.gh-issue-162894.U_2TCv.rst @@ -0,0 +1,4 @@ +:c:func:`PyList_Append`, :c:func:`PyList_Extend` and :c:func:`PyList_Insert` +can no longer shrink the list. It avoids shrinking a list created by +``PyList_New(n)`` followed by ``Py_SET_SIZE(list, 0)`` to preallocate *n* +items. Patch by Victor Stinner. diff --git a/Modules/_testcapi/list.c b/Modules/_testcapi/list.c index 530b47780ac94e..ea18c917c5fcf5 100644 --- a/Modules/_testcapi/list.c +++ b/Modules/_testcapi/list.c @@ -1,6 +1,11 @@ +// Get _Py_LIST_SMALL_ALLOCATED from "pycore_list.h" +#define PYTESTCAPI_NEED_INTERNAL_API + #include "parts.h" #include "util.h" +#include "pycore_list.h" // _Py_LIST_SMALL_ALLOCATED + static PyObject * list_get_size(PyObject *Py_UNUSED(module), PyObject *obj) @@ -10,6 +15,15 @@ list_get_size(PyObject *Py_UNUSED(module), PyObject *obj) } +static PyObject * +list_get_allocated(PyObject *Py_UNUSED(module), PyObject *obj) +{ + NULLABLE(obj); + PyListObject *list = (PyListObject*)obj; + return PyLong_FromSsize_t(list->allocated); +} + + static PyObject * list_get_item(PyObject *Py_UNUSED(module), PyObject *args) { @@ -110,11 +124,18 @@ static PyMethodDef test_methods[] = { {"list_clear", list_clear, METH_O}, {"list_extend", list_extend, METH_VARARGS}, {"test_list_api", test_list_api, METH_NOARGS}, + {"list_get_allocated", list_get_allocated, METH_O}, {NULL}, }; int _PyTestCapi_Init_List(PyObject *m) { - return PyModule_AddFunctions(m, test_methods); + if (PyModule_AddFunctions(m, test_methods) < 0) { + return -1; + } + if (PyModule_AddIntConstant(m, "LIST_SMALL_ALLOCATED", _Py_LIST_SMALL_ALLOCATED) < 0) { + return -1; + } + return 0; } diff --git a/Objects/listobject.c b/Objects/listobject.c index c5fe704df0e23d..86a9965eec32cd 100644 --- a/Objects/listobject.c +++ b/Objects/listobject.c @@ -91,15 +91,17 @@ ensure_shared_on_resize(PyListObject *self) #endif } -#define LIST_SMALL_ALLOCATED 32 +#define LIST_SMALL_ALLOCATED _Py_LIST_SMALL_ALLOCATED static int py_list_resize(PyListObject *self, Py_ssize_t newsize); -/* Ensure ob_item has room for at least newsize elements, and set +/* Grow a list. + * + * Ensure ob_item has room for at least newsize elements, and set * ob_size to newsize. If newsize > ob_size on entry, the content * of the new slots at exit is undefined heap trash; it's the caller's * responsibility to overwrite them with sane values. - * The number of allocated elements may grow, shrink, or stay the same. + * The number of allocated elements may grow, or stay the same. * Failure is impossible if newsize <= self.allocated on entry. * Note that self->ob_item may change, and even if newsize is less * than ob_size on entry. @@ -110,6 +112,27 @@ static int py_list_resize(PyListObject *self, Py_ssize_t newsize); static inline Py_ALWAYS_INLINE int list_resize(PyListObject *self, Py_ssize_t newsize) { + // list_resize() must only be called to grow the list + assert(Py_SIZE(self) <= newsize); + Py_ssize_t allocated = self->allocated; + + /* Bypass realloc() when a previous overallocation is large enough + to accommodate the newsize. */ + if (newsize <= allocated && (self->ob_item != NULL || newsize == 0)) { + Py_SET_SIZE(self, newsize); + return 0; + } + return py_list_resize(self, newsize); +} + +/* Shrink a list. Similar to list_resize(), but it can shrink the list if + * needed. The function cannot fail: on memory allocation failure, leave the + * list items unchanged (only change the list size). */ +static inline Py_ALWAYS_INLINE void +list_resize_shrink(PyListObject *self, Py_ssize_t newsize) +{ + // list_resize_shrink() must only be called to shrink the list + assert(0 <= newsize && newsize <= Py_SIZE(self)); Py_ssize_t allocated = self->allocated; /* Bypass realloc() when a previous overallocation is large enough @@ -123,12 +146,19 @@ list_resize(PyListObject *self, Py_ssize_t newsize) { assert(self->ob_item != NULL || newsize == 0); Py_SET_SIZE(self, newsize); - return 0; + return; } - return py_list_resize(self, newsize); + + int res = py_list_resize(self, newsize); +#ifndef NDEBUG + assert(res == 0); +#else + (void)res; +#endif } -/* Slow path of list_resize(): allocate or reallocate ob_item. */ +/* Slow path of list_resize() and list_resize_shrink(): + * allocate or reallocate ob_item. */ static int py_list_resize(PyListObject *self, Py_ssize_t newsize) { @@ -1065,7 +1095,7 @@ list_ass_slice_lock_held(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyO if (d < 0) { /* Delete -d items */ Py_ssize_t tail = Py_SIZE(a) - ihigh; ptr_wise_atomic_memmove(a, &item[ihigh+d], &item[ihigh], tail); - (void)list_resize(a, Py_SIZE(a) + d); // NB: shrinking a list can't fail + list_resize_shrink(a, Py_SIZE(a) + d); // NB: shrinking a list can't fail item = a->ob_item; } else if (d > 0) { /* Insert d items */ @@ -1214,7 +1244,7 @@ list_ass_item_impl(PyListObject *a, Py_ssize_t i, PyObject *v) if (i < size - 1) { list_shift_items_left_lock_held(a, i, size - 1); } - list_resize(a, size - 1); // NB: shrinking a list can't fail + list_resize_shrink(a, size - 1); // NB: shrinking a list can't fail } else { FT_ATOMIC_STORE_PTR_RELEASE(a->ob_item[i], Py_NewRef(v)); @@ -1394,8 +1424,7 @@ list_extend_iter_lock_held(PyListObject *self, PyObject *iterable) /* Cut back result list if initial guess was too large. */ if (Py_SIZE(self) < self->allocated) { - if (list_resize(self, Py_SIZE(self)) < 0) - goto error; + list_resize_shrink(self, Py_SIZE(self)); } Py_DECREF(it); @@ -1667,7 +1696,7 @@ list_pop_impl(PyListObject *self, Py_ssize_t index) ptr_wise_atomic_memmove(self, &items[index], &items[index+1], size_after_pop - index); } - list_resize(self, size_after_pop); // NB: shrinking a list can't fail + list_resize_shrink(self, size_after_pop); // NB: shrinking a list can't fail return v; } @@ -3835,7 +3864,6 @@ list_ass_subscript_lock_held(PyObject *_self, PyObject *item, PyObject *value) PyObject **garbage; size_t cur; Py_ssize_t i; - int res; Py_ssize_t slicelength = adjust_slice_indexes(self, &start, &stop, step); @@ -3885,15 +3913,14 @@ list_ass_subscript_lock_held(PyObject *_self, PyObject *item, PyObject *value) self->ob_item + cur, Py_SIZE(self) - cur); } - Py_SET_SIZE(self, Py_SIZE(self) - slicelength); - res = list_resize(self, Py_SIZE(self)); + list_resize_shrink(self, Py_SIZE(self) - slicelength); for (i = 0; i < slicelength; i++) { Py_DECREF(garbage[i]); } PyMem_Free(garbage); - return res; + return 0; } else { /* assign slice */