Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Include/internal/pycore_list.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 *);
Expand Down
80 changes: 80 additions & 0 deletions Lib/test/test_capi/test_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,86 @@ def test_uninitialized_list_repr(self):
lst = _testlimitedcapi.list_new(3)
self.assertEqual(repr(lst), '[<NULL>, <NULL>, <NULL>]')

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()
Original file line number Diff line number Diff line change
@@ -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.
23 changes: 22 additions & 1 deletion Modules/_testcapi/list.c
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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)
{
Expand Down Expand Up @@ -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;
}
57 changes: 42 additions & 15 deletions Objects/listobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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)
{
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe // NB: shrinking a list can't fail comments can now be removed, since list_resize_shrink() return type is void. Now the function cannot fail at the C level.

item = a->ob_item;
}
else if (d > 0) { /* Insert d items */
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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 */
Expand Down
Loading