Skip to content

Commit c8d892e

Browse files
authored
gh-158660: Add can_shrink parameter to list_resize() (#162969)
PyListBuilder uses can_shrink=0 (only shrink the list in Finish()), whereas existing PyList functions, such as PyList_Append() and PyList_Extend(), use can_shrink=1 for backward compatibility. * Add list_shrink() function. * Add tests on list methods shrinking the list. * Add builder.get_allocated() in _testcapi. * list_ass_subscript_lock_held() avoids Py_SET_SIZE() and pass directly the new size to list_resize().
1 parent 35f2bb9 commit c8d892e

3 files changed

Lines changed: 246 additions & 66 deletions

File tree

‎Lib/test/test_capi/test_list.py‎

Lines changed: 112 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,85 @@ def test_uninitialized_list_repr(self):
364364
lst = _testlimitedcapi.list_new(3)
365365
self.assertEqual(repr(lst), '[<NULL>, <NULL>, <NULL>]')
366366

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

368447
class ListBuilderTests(unittest.TestCase):
369448
def create_builder(self, size):
@@ -515,23 +594,49 @@ def test_empty(self):
515594
expected = size
516595
self.assertEqual(list_get_allocated(result), expected)
517596

597+
@staticmethod
598+
def compute_allocated(size):
599+
return ((size + (size >> 3) + 6) & ~3)
600+
601+
def test_no_shrink(self):
602+
# PyListBuilder methods must not shrink the list before Finish()
603+
get_allocated = _testcapi._list_get_allocated
604+
605+
def check_allocated():
606+
self.assertEqual(builder.get_allocated(), alloc)
607+
608+
alloc = 2048
609+
builder = self.create_builder(alloc)
610+
check_allocated()
611+
612+
builder.append('a')
613+
check_allocated()
614+
builder.append_steal('b')
615+
check_allocated()
616+
builder.extend(('c',))
617+
check_allocated()
618+
builder.extend_array(('d',))
619+
check_allocated()
620+
builder.extend_array(('e',))
621+
check_allocated()
622+
623+
result = builder.finish()
624+
self.list_equal(result, 'abcde')
625+
self.assertEqual(get_allocated(result),
626+
self.compute_allocated(len(result)))
627+
518628
def test_finish_shrink(self):
519629
# PyListBuilder_Finish() shrinks the list if its allocated size
520630
# is way too big
521631
list_get_allocated = _testcapi._list_get_allocated
522632

523-
def compute_allocated(size):
524-
return (size + (size >> 3) + 6) & ~3
525-
526633
def check_allocated(items, alloc, expected=None):
527634
builder = self.create_builder(alloc)
528-
# Don't use PyListBuilder_Extend() since it can shrink the list
529-
for item in items:
530-
builder.append(item)
635+
builder.extend(items)
531636
result = builder.finish()
532637
self.list_equal(result, list(items))
533638
if expected is None:
534-
expected = compute_allocated(len(items))
639+
expected = self.compute_allocated(len(items))
535640
self.assertEqual(list_get_allocated(result), expected)
536641

537642
# small list

‎Modules/_testlimitedcapi/list.c‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,12 +422,58 @@ builder_discard(PyObject *self_raw, PyObject *Py_UNUSED(args))
422422
}
423423

424424

425+
static PyObject*
426+
get_allocated_func(void)
427+
{
428+
PyObject *modname = PyUnicode_FromString("_testcapi");
429+
if (modname == NULL) {
430+
return NULL;
431+
}
432+
PyObject *mod = PyImport_Import(modname);
433+
Py_DECREF(modname);
434+
if (mod == NULL) {
435+
return NULL;
436+
}
437+
438+
PyObject *attrname = PyUnicode_FromString("_list_get_allocated");
439+
if (attrname == NULL) {
440+
Py_DECREF(mod);
441+
return NULL;
442+
}
443+
PyObject *result = PyObject_GetAttr(mod, attrname);
444+
Py_DECREF(mod);
445+
Py_DECREF(attrname);
446+
return result;
447+
}
448+
449+
450+
static PyObject*
451+
builder_get_allocated(PyObject *self_raw, PyObject *Py_UNUSED(args))
452+
{
453+
BuilderObject *self = BuilderObject_GET(self_raw);
454+
if (builder_check(self) < 0) {
455+
return NULL;
456+
}
457+
458+
PyObject *get_allocated = get_allocated_func();
459+
if (get_allocated == NULL) {
460+
return NULL;
461+
}
462+
463+
PyObject *list = (PyObject *)self->builder;
464+
PyObject *res = PyObject_CallFunctionObjArgs(get_allocated, list, NULL);
465+
Py_DECREF(get_allocated);
466+
return res;
467+
}
468+
469+
425470
static PyMethodDef builder_methods[] = {
426471
{"append", builder_append, METH_O},
427472
{"append_steal", builder_append_steal, METH_O},
428473
{"extend", builder_extend, METH_O},
429474
{"extend_array", builder_extend_array, METH_O},
430475
{"extend_array_steal", builder_extend_array_steal, METH_O},
476+
{"get_allocated", builder_get_allocated, METH_NOARGS},
431477
{"finish", builder_finish, METH_NOARGS},
432478
{"discard", builder_discard, METH_NOARGS},
433479
{NULL, NULL} // sentinel

0 commit comments

Comments
 (0)