Skip to content

Commit 2153daf

Browse files
bpo-39829: Fix __len__() is called twice in list() constructor (GH-31816)
1 parent 690490e commit 2153daf

File tree

3 files changed

+14
-18
lines changed

3 files changed

+14
-18
lines changed

Misc/ACKS

+1-1
Original file line numberDiff line numberDiff line change
@@ -1336,6 +1336,7 @@ William Park
13361336
Claude Paroz
13371337
Heikki Partanen
13381338
Harri Pasanen
1339+
Jeremiah Gabriel Pascual
13391340
Gaël Pasgrimaud
13401341
Feanil Patel
13411342
Ashish Nitin Patil
@@ -1864,7 +1865,6 @@ Kurt Vile
18641865
Norman Vine
18651866
Pauli Virtanen
18661867
Frank Visser
1867-
Jeremiah Vivian (Pascual)
18681868
Johannes Vogel
18691869
Michael Vogt
18701870
Radu Voicilas
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Removed the ``__len__()`` call when initializing a list and moved initializing to ``list_extend``. Patch by Jeremiah Pascual.

Objects/listobject.c

+12-17
Original file line numberDiff line numberDiff line change
@@ -865,7 +865,6 @@ list_extend(PyListObject *self, PyObject *iterable)
865865
PyObject *it; /* iter(v) */
866866
Py_ssize_t m; /* size of self */
867867
Py_ssize_t n; /* guess for size of iterable */
868-
Py_ssize_t mn; /* m + n */
869868
Py_ssize_t i;
870869
PyObject *(*iternext)(PyObject *);
871870

@@ -889,7 +888,13 @@ list_extend(PyListObject *self, PyObject *iterable)
889888
/* It should not be possible to allocate a list large enough to cause
890889
an overflow on any relevant platform */
891890
assert(m < PY_SSIZE_T_MAX - n);
892-
if (list_resize(self, m + n) < 0) {
891+
if (self->ob_item == NULL) {
892+
if (list_preallocate_exact(self, n) < 0) {
893+
return NULL;
894+
}
895+
Py_SET_SIZE(self, n);
896+
}
897+
else if (list_resize(self, m + n) < 0) {
893898
Py_DECREF(iterable);
894899
return NULL;
895900
}
@@ -928,10 +933,13 @@ list_extend(PyListObject *self, PyObject *iterable)
928933
* eventually run out of memory during the loop.
929934
*/
930935
}
936+
else if (self->ob_item == NULL) {
937+
if (n && list_preallocate_exact(self, n) < 0)
938+
goto error;
939+
}
931940
else {
932-
mn = m + n;
933941
/* Make room. */
934-
if (list_resize(self, mn) < 0)
942+
if (list_resize(self, m + n) < 0)
935943
goto error;
936944
/* Make the list sane again. */
937945
Py_SET_SIZE(self, m);
@@ -2814,19 +2822,6 @@ list___init___impl(PyListObject *self, PyObject *iterable)
28142822
(void)_list_clear(self);
28152823
}
28162824
if (iterable != NULL) {
2817-
if (_PyObject_HasLen(iterable)) {
2818-
Py_ssize_t iter_len = PyObject_Size(iterable);
2819-
if (iter_len == -1) {
2820-
if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
2821-
return -1;
2822-
}
2823-
PyErr_Clear();
2824-
}
2825-
if (iter_len > 0 && self->ob_item == NULL
2826-
&& list_preallocate_exact(self, iter_len)) {
2827-
return -1;
2828-
}
2829-
}
28302825
PyObject *rv = list_extend(self, iterable);
28312826
if (rv == NULL)
28322827
return -1;

0 commit comments

Comments
 (0)