@@ -583,6 +583,7 @@ list_repr_impl(PyListObject *v)
583583 /* "[" + "1" + ", 2" * (len - 1) + "]" */
584584 Py_ssize_t prealloc = 1 + 1 + (2 + 1 ) * (Py_SIZE (v ) - 1 ) + 1 ;
585585 PyUnicodeWriter * writer = PyUnicodeWriter_Create (prealloc );
586+ PyObject * item = NULL ;
586587 if (writer == NULL ) {
587588 goto error ;
588589 }
@@ -594,6 +595,13 @@ list_repr_impl(PyListObject *v)
594595 /* Do repr() on each element. Note that this may mutate the list,
595596 so must refetch the list size on each iteration. */
596597 for (Py_ssize_t i = 0 ; i < Py_SIZE (v ); ++ i ) {
598+ item = list_get_item_ref (v , i );
599+ if (item == NULL ) {
600+ // List truncated while iterating on it
601+ PyErr_Clear ();
602+ break ;
603+ }
604+
597605 if (i > 0 ) {
598606 if (PyUnicodeWriter_WriteChar (writer , ',' ) < 0 ) {
599607 goto error ;
@@ -603,9 +611,10 @@ list_repr_impl(PyListObject *v)
603611 }
604612 }
605613
606- if (PyUnicodeWriter_WriteRepr (writer , v -> ob_item [ i ] ) < 0 ) {
614+ if (PyUnicodeWriter_WriteRepr (writer , item ) < 0 ) {
607615 goto error ;
608616 }
617+ Py_CLEAR (item );
609618 }
610619
611620 if (PyUnicodeWriter_WriteChar (writer , ']' ) < 0 ) {
@@ -616,6 +625,7 @@ list_repr_impl(PyListObject *v)
616625 return PyUnicodeWriter_Finish (writer );
617626
618627error :
628+ Py_XDECREF (item );
619629 PyUnicodeWriter_Discard (writer );
620630 Py_ReprLeave ((PyObject * )v );
621631 return NULL ;
0 commit comments