Skip to content

Commit bc8288b

Browse files
committed
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()
1 parent c37d06e commit bc8288b

5 files changed

Lines changed: 150 additions & 16 deletions

File tree

‎Include/internal/pycore_list.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ extern "C" {
1212
#include "pycore_stackref.h"
1313
#endif
1414

15+
#define _Py_LIST_SMALL_ALLOCATED 32
16+
1517
PyAPI_FUNC(PyObject*) _PyList_Extend(PyListObject *, PyObject *);
1618
PyAPI_FUNC(PyObject) *_PyList_SliceSubscript(PyObject*, PyObject*);
1719
PyAPI_FUNC(PyObject *) _PyList_BinarySlice(PyObject *, PyObject *, PyObject *);

‎Lib/test/test_capi/test_list.py‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,86 @@ def test_uninitialized_list_repr(self):
358358
lst = _testlimitedcapi.list_new(3)
359359
self.assertEqual(repr(lst), '[<NULL>, <NULL>, <NULL>]')
360360

361+
def test_shrink(self):
362+
# Check list methods shrinking the list: methods calling
363+
# list_resize_shrink().
364+
get_allocated = _testcapi.list_get_allocated
365+
LIST_SMALL_ALLOCATED = _testcapi.LIST_SMALL_ALLOCATED
366+
367+
def check_allocated(lst, expected_length):
368+
size = len(lst)
369+
self.assertEqual(size, expected_length)
370+
371+
# See py_list_resize() in Objects/listobject.c
372+
expected = max(size + (size >> 1) + 6, LIST_SMALL_ALLOCATED)
373+
self.assertLessEqual(get_allocated(lst), expected)
374+
375+
# del list[start:end]
376+
lst = list(range(1024))
377+
self.assertGreaterEqual(get_allocated(lst), 1024)
378+
del lst[128:]
379+
check_allocated(lst, 128)
380+
del lst[8:]
381+
check_allocated(lst, 8)
382+
383+
# del list[start:end:step] with step != 1
384+
lst = list(range(1024))
385+
self.assertGreaterEqual(get_allocated(lst), 1024)
386+
del lst[::2]
387+
del lst[::2]
388+
check_allocated(lst, 256)
389+
del lst[::2]
390+
del lst[::2]
391+
del lst[::2]
392+
del lst[::2]
393+
check_allocated(lst, 16)
394+
395+
# del list[index]
396+
lst = list(range(1024))
397+
self.assertGreaterEqual(get_allocated(lst), 1024)
398+
for _ in range(1024 - 128):
399+
del lst[-1]
400+
check_allocated(lst, 128)
401+
for _ in range(120):
402+
del lst[-1]
403+
check_allocated(lst, 8)
404+
405+
# list.pop()
406+
lst = list(range(1024))
407+
self.assertGreaterEqual(get_allocated(lst), 1024)
408+
for _ in range(1024 - 128):
409+
lst.pop()
410+
check_allocated(lst, 128)
411+
for _ in range(120):
412+
lst.pop()
413+
check_allocated(lst, 8)
414+
415+
# Iterator with a bad __length_hint__() estimation
416+
class Iterator:
417+
def __init__(self, items):
418+
self.data = tuple(items)
419+
self.pos = 0
420+
421+
def __iter__(self):
422+
return self
423+
424+
def __length_hint__(self):
425+
return len(self.data) * 8
426+
427+
def __next__(self):
428+
try:
429+
item = self.data[self.pos]
430+
except IndexError:
431+
raise StopIteration
432+
self.pos += 1
433+
return item
434+
435+
# list.extend(iterator) with bad __length_hint__() estimation
436+
lst = []
437+
items = list(range(8))
438+
lst.extend(Iterator(items))
439+
check_allocated(lst, len(items))
440+
361441

362442
if __name__ == "__main__":
363443
unittest.main()
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
:c:func:`PyList_Append`, :c:func:`PyList_Extend` and :c:func:`PyList_Insert`
2+
can no longer shrink the list. It avoids shrinking a list created by
3+
``PyList_New(n)`` followed by ``Py_SET_SIZE(list, 0)`` to preallocate *n*
4+
items. Patch by Victor Stinner.

‎Modules/_testcapi/list.c‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
1+
// Get _Py_LIST_SMALL_ALLOCATED from "pycore_list.h"
2+
#define PYTESTCAPI_NEED_INTERNAL_API
3+
14
#include "parts.h"
25
#include "util.h"
36

7+
#include "pycore_list.h" // _Py_LIST_SMALL_ALLOCATED
8+
49

510
static PyObject *
611
list_get_size(PyObject *Py_UNUSED(module), PyObject *obj)
@@ -10,6 +15,15 @@ list_get_size(PyObject *Py_UNUSED(module), PyObject *obj)
1015
}
1116

1217

18+
static PyObject *
19+
list_get_allocated(PyObject *Py_UNUSED(module), PyObject *obj)
20+
{
21+
NULLABLE(obj);
22+
PyListObject *list = (PyListObject*)obj;
23+
return PyLong_FromSsize_t(list->allocated);
24+
}
25+
26+
1327
static PyObject *
1428
list_get_item(PyObject *Py_UNUSED(module), PyObject *args)
1529
{
@@ -110,11 +124,18 @@ static PyMethodDef test_methods[] = {
110124
{"list_clear", list_clear, METH_O},
111125
{"list_extend", list_extend, METH_VARARGS},
112126
{"test_list_api", test_list_api, METH_NOARGS},
127+
{"list_get_allocated", list_get_allocated, METH_O},
113128
{NULL},
114129
};
115130

116131
int
117132
_PyTestCapi_Init_List(PyObject *m)
118133
{
119-
return PyModule_AddFunctions(m, test_methods);
134+
if (PyModule_AddFunctions(m, test_methods) < 0) {
135+
return -1;
136+
}
137+
if (PyModule_AddIntConstant(m, "LIST_SMALL_ALLOCATED", _Py_LIST_SMALL_ALLOCATED) < 0) {
138+
return -1;
139+
}
140+
return 0;
120141
}

‎Objects/listobject.c‎

Lines changed: 42 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -91,15 +91,17 @@ ensure_shared_on_resize(PyListObject *self)
9191
#endif
9292
}
9393

94-
#define LIST_SMALL_ALLOCATED 32
94+
#define LIST_SMALL_ALLOCATED _Py_LIST_SMALL_ALLOCATED
9595

9696
static int py_list_resize(PyListObject *self, Py_ssize_t newsize);
9797

98-
/* Ensure ob_item has room for at least newsize elements, and set
98+
/* Grow a list.
99+
*
100+
* Ensure ob_item has room for at least newsize elements, and set
99101
* ob_size to newsize. If newsize > ob_size on entry, the content
100102
* of the new slots at exit is undefined heap trash; it's the caller's
101103
* responsibility to overwrite them with sane values.
102-
* The number of allocated elements may grow, shrink, or stay the same.
104+
* The number of allocated elements may grow, or stay the same.
103105
* Failure is impossible if newsize <= self.allocated on entry.
104106
* Note that self->ob_item may change, and even if newsize is less
105107
* than ob_size on entry.
@@ -110,6 +112,27 @@ static int py_list_resize(PyListObject *self, Py_ssize_t newsize);
110112
static inline Py_ALWAYS_INLINE int
111113
list_resize(PyListObject *self, Py_ssize_t newsize)
112114
{
115+
// list_resize() must only be called to grow the list
116+
assert(Py_SIZE(self) <= newsize);
117+
Py_ssize_t allocated = self->allocated;
118+
119+
/* Bypass realloc() when a previous overallocation is large enough
120+
to accommodate the newsize. */
121+
if (newsize <= allocated && (self->ob_item != NULL || newsize == 0)) {
122+
Py_SET_SIZE(self, newsize);
123+
return 0;
124+
}
125+
return py_list_resize(self, newsize);
126+
}
127+
128+
/* Shrink a list. Similar to list_resize(), but it can shrink the list if
129+
* needed. The function cannot fail: on memory allocation failure, leave the
130+
* list items unchanged (only change the list size). */
131+
static inline Py_ALWAYS_INLINE void
132+
list_resize_shrink(PyListObject *self, Py_ssize_t newsize)
133+
{
134+
// list_resize_shrink() must only be called to shrink the list
135+
assert(0 <= newsize && newsize <= Py_SIZE(self));
113136
Py_ssize_t allocated = self->allocated;
114137

115138
/* Bypass realloc() when a previous overallocation is large enough
@@ -123,12 +146,19 @@ list_resize(PyListObject *self, Py_ssize_t newsize)
123146
{
124147
assert(self->ob_item != NULL || newsize == 0);
125148
Py_SET_SIZE(self, newsize);
126-
return 0;
149+
return;
127150
}
128-
return py_list_resize(self, newsize);
151+
152+
int res = py_list_resize(self, newsize);
153+
#ifndef NDEBUG
154+
assert(res == 0);
155+
#else
156+
(void)res;
157+
#endif
129158
}
130159

131-
/* Slow path of list_resize(): allocate or reallocate ob_item. */
160+
/* Slow path of list_resize() and list_resize_shrink():
161+
* allocate or reallocate ob_item. */
132162
static int
133163
py_list_resize(PyListObject *self, Py_ssize_t newsize)
134164
{
@@ -1065,7 +1095,7 @@ list_ass_slice_lock_held(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyO
10651095
if (d < 0) { /* Delete -d items */
10661096
Py_ssize_t tail = Py_SIZE(a) - ihigh;
10671097
ptr_wise_atomic_memmove(a, &item[ihigh+d], &item[ihigh], tail);
1068-
(void)list_resize(a, Py_SIZE(a) + d); // NB: shrinking a list can't fail
1098+
list_resize_shrink(a, Py_SIZE(a) + d); // NB: shrinking a list can't fail
10691099
item = a->ob_item;
10701100
}
10711101
else if (d > 0) { /* Insert d items */
@@ -1214,7 +1244,7 @@ list_ass_item_impl(PyListObject *a, Py_ssize_t i, PyObject *v)
12141244
if (i < size - 1) {
12151245
list_shift_items_left_lock_held(a, i, size - 1);
12161246
}
1217-
list_resize(a, size - 1); // NB: shrinking a list can't fail
1247+
list_resize_shrink(a, size - 1); // NB: shrinking a list can't fail
12181248
}
12191249
else {
12201250
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)
13941424

13951425
/* Cut back result list if initial guess was too large. */
13961426
if (Py_SIZE(self) < self->allocated) {
1397-
if (list_resize(self, Py_SIZE(self)) < 0)
1398-
goto error;
1427+
list_resize_shrink(self, Py_SIZE(self));
13991428
}
14001429

14011430
Py_DECREF(it);
@@ -1667,7 +1696,7 @@ list_pop_impl(PyListObject *self, Py_ssize_t index)
16671696
ptr_wise_atomic_memmove(self, &items[index], &items[index+1],
16681697
size_after_pop - index);
16691698
}
1670-
list_resize(self, size_after_pop); // NB: shrinking a list can't fail
1699+
list_resize_shrink(self, size_after_pop); // NB: shrinking a list can't fail
16711700
return v;
16721701
}
16731702

@@ -3835,7 +3864,6 @@ list_ass_subscript_lock_held(PyObject *_self, PyObject *item, PyObject *value)
38353864
PyObject **garbage;
38363865
size_t cur;
38373866
Py_ssize_t i;
3838-
int res;
38393867

38403868
Py_ssize_t slicelength = adjust_slice_indexes(self, &start, &stop,
38413869
step);
@@ -3885,15 +3913,14 @@ list_ass_subscript_lock_held(PyObject *_self, PyObject *item, PyObject *value)
38853913
self->ob_item + cur, Py_SIZE(self) - cur);
38863914
}
38873915

3888-
Py_SET_SIZE(self, Py_SIZE(self) - slicelength);
3889-
res = list_resize(self, Py_SIZE(self));
3916+
list_resize_shrink(self, Py_SIZE(self) - slicelength);
38903917

38913918
for (i = 0; i < slicelength; i++) {
38923919
Py_DECREF(garbage[i]);
38933920
}
38943921
PyMem_Free(garbage);
38953922

3896-
return res;
3923+
return 0;
38973924
}
38983925
else {
38993926
/* assign slice */

0 commit comments

Comments
 (0)