From 0823270cde4f7914cde1140a5c76068846102461 Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Sun, 8 Nov 2026 19:26:16 +0100 Subject: [PATCH 1/3] gh-161635: Add PyList_AsTupleAndClear() function * Rename _PyList_AsTupleAndClear() to PyList_AsTupleAndClear(). * The function now raises TypeError if the argument is not a list. * Add documentation and tests. --- Doc/c-api/list.rst | 25 +++++++++++++++++++++++++ Include/cpython/listobject.h | 1 + Include/internal/pycore_list.h | 1 - Lib/test/test_capi/test_list.py | 22 ++++++++++++++++++++++ Modules/_testcapi/list.c | 10 ++++++++++ Objects/abstract.c | 2 +- Objects/listobject.c | 8 +++++++- Python/intrinsics.c | 3 +-- 8 files changed, 67 insertions(+), 5 deletions(-) diff --git a/Doc/c-api/list.rst b/Doc/c-api/list.rst index 21769c4c5c869c8..edc4572e68f80dd 100644 --- a/Doc/c-api/list.rst +++ b/Doc/c-api/list.rst @@ -227,3 +227,28 @@ List Objects Return a new tuple object containing the contents of *list*; equivalent to ``tuple(list)``. + + +.. c:function:: PyObject* PyList_AsTupleAndClear(PyObject *list) + + .. index:: pair: built-in function; tuple + + Return a new :class:`tuple` created from the existing :class:`list` + instance. + + Transfers all items from *list* to the newly allocated :class:`tuple`. + Clears the input *list* on success. + + Return a new :class:`tuple` on success. + Set an exception and return ``NULL`` on error. + + This function is intended for building a :class:`tuple` instance via a + temporary *list* that is not exposed to user code. + To "freeze" an arbitrary list, for example one received from the user as an + argument, prefer :c:func:`PyList_AsTuple` to leave the source intact. + + .. impl-detail:: + + Works with O(1) complexity. + + .. versionadded:: next diff --git a/Include/cpython/listobject.h b/Include/cpython/listobject.h index 49f5e8d6d1a0d6c..f0095b296179288 100644 --- a/Include/cpython/listobject.h +++ b/Include/cpython/listobject.h @@ -51,3 +51,4 @@ PyList_SET_ITEM(PyObject *op, Py_ssize_t index, PyObject *value) { PyAPI_FUNC(int) PyList_Extend(PyObject *self, PyObject *iterable); PyAPI_FUNC(int) PyList_Clear(PyObject *self); +PyAPI_FUNC(PyObject*) PyList_AsTupleAndClear(PyObject *v); diff --git a/Include/internal/pycore_list.h b/Include/internal/pycore_list.h index df0d00f752573b5..587cca6ab451a5e 100644 --- a/Include/internal/pycore_list.h +++ b/Include/internal/pycore_list.h @@ -75,7 +75,6 @@ typedef struct { union _PyStackRef; PyAPI_FUNC(PyObject *)_PyList_FromStackRefStealOnSuccess(const union _PyStackRef *src, Py_ssize_t n); -PyAPI_FUNC(PyObject *)_PyList_AsTupleAndClear(PyListObject *v); #ifdef __cplusplus } diff --git a/Lib/test/test_capi/test_list.py b/Lib/test/test_capi/test_list.py index b95b8ba960bd8b2..50dd441fe036fc0 100644 --- a/Lib/test/test_capi/test_list.py +++ b/Lib/test/test_capi/test_list.py @@ -354,6 +354,28 @@ def test_uninitialized_list_repr(self): lst = _testlimitedcapi.list_new(3) self.assertEqual(repr(lst), '[, , ]') + def test_as_tuple_and_clear(self): + list_as_tuple_and_clear = _testcapi.list_as_tuple_and_clear + + lst = list("abc") + self.assertEqual(list_as_tuple_and_clear(lst), ('a', 'b', 'c')) + self.assertEqual(lst, []) + + lst = list(range(4096)) # test larger list + self.assertEqual(list_as_tuple_and_clear(lst), tuple(range(4096))) + self.assertEqual(lst, []) + + lst = [] # empty list + self.assertIs(list_as_tuple_and_clear(lst), ()) + self.assertEqual(lst, []) + + # CRASHES list_as_tuple_and_clear(NULL) + + # Wrong type + for obj in (tuple("abc"), {'key': 'value'}, 123): + with self.subTest(obj=obj): + self.assertRaises(TypeError, list_as_tuple_and_clear, obj) + if __name__ == "__main__": unittest.main() diff --git a/Modules/_testcapi/list.c b/Modules/_testcapi/list.c index 530b47780ac94e2..bdd340e9831b0ab 100644 --- a/Modules/_testcapi/list.c +++ b/Modules/_testcapi/list.c @@ -103,6 +103,15 @@ test_list_api(PyObject *self, PyObject *Py_UNUSED(ignored)) } +// Test PyList_AsTupleAndClear() +static PyObject* +list_as_tuple_and_clear(PyObject *self, PyObject *arg) +{ + NULLABLE(arg); + return PyList_AsTupleAndClear(arg); +} + + static PyMethodDef test_methods[] = { {"list_get_size", list_get_size, METH_O}, {"list_get_item", list_get_item, METH_VARARGS}, @@ -110,6 +119,7 @@ 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_as_tuple_and_clear", list_as_tuple_and_clear, METH_O}, {NULL}, }; diff --git a/Objects/abstract.c b/Objects/abstract.c index da2a0b0c285b52b..8a49baecbcb58ac 100644 --- a/Objects/abstract.c +++ b/Objects/abstract.c @@ -2066,7 +2066,7 @@ PySequence_Tuple(PyObject *v) } } Py_DECREF(it); - PyObject *res = _PyList_AsTupleAndClear(list); + PyObject *res = PyList_AsTupleAndClear(_PyObject_CAST(list)); Py_DECREF(list); return res; fail: diff --git a/Objects/listobject.c b/Objects/listobject.c index 4384a850780b7fd..69f48f0a396af7e 100644 --- a/Objects/listobject.c +++ b/Objects/listobject.c @@ -3346,8 +3346,14 @@ PyList_AsTuple(PyObject *v) } PyObject * -_PyList_AsTupleAndClear(PyListObject *self) +PyList_AsTupleAndClear(PyObject *v) { + if (!PyList_Check(v)) { + PyErr_Format(PyExc_TypeError, "expected a list, got %T", v); + return NULL; + } + PyListObject* self = (PyListObject*)v; + assert(self != NULL); PyObject *ret; if (self->ob_item == NULL) { diff --git a/Python/intrinsics.c b/Python/intrinsics.c index dfa81baa654e123..0f72bab9451a545 100644 --- a/Python/intrinsics.c +++ b/Python/intrinsics.c @@ -7,7 +7,6 @@ #include "pycore_genobject.h" // _PyAsyncGenValueWrapperNew #include "pycore_interpframe.h" // _PyFrame_GetLocals() #include "pycore_intrinsics.h" // INTRINSIC_PRINT -#include "pycore_list.h" // _PyList_AsTupleAndClear() #include "pycore_object.h" // _PyObject_IsUniquelyReferenced() #include "pycore_setobject.h" // _PySet_Freeze() #include "pycore_pyerrors.h" // _PyErr_SetString() @@ -198,7 +197,7 @@ list_to_tuple(PyThreadState* unused, PyObject *v) into the tuple instead of copying them. */ assert(PyList_CheckExact(v)); assert(_PyObject_IsUniquelyReferenced(v)); - return _PyList_AsTupleAndClear((PyListObject *)v); + return PyList_AsTupleAndClear(v); } static PyObject * From c8b5153b528135f6d5a519b674661c315958c63b Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Sun, 8 Nov 2026 20:27:51 +0100 Subject: [PATCH 2/3] Test also list subclass --- Lib/test/test_capi/test_list.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_capi/test_list.py b/Lib/test/test_capi/test_list.py index 50dd441fe036fc0..30fb2a6522e2f1b 100644 --- a/Lib/test/test_capi/test_list.py +++ b/Lib/test/test_capi/test_list.py @@ -360,12 +360,20 @@ def test_as_tuple_and_clear(self): lst = list("abc") self.assertEqual(list_as_tuple_and_clear(lst), ('a', 'b', 'c')) self.assertEqual(lst, []) + self.assertEqual(type(lst), list) + + expected = tuple(object() for _ in range(10)) + sub = ListSubclass(expected) + self.assertEqual(list_as_tuple_and_clear(sub), expected) + self.assertEqual(sub, []) + self.assertEqual(type(sub), ListSubclass) lst = list(range(4096)) # test larger list self.assertEqual(list_as_tuple_and_clear(lst), tuple(range(4096))) self.assertEqual(lst, []) - lst = [] # empty list + # Get the empty tuple singleton if the list is empty + lst = [] self.assertIs(list_as_tuple_and_clear(lst), ()) self.assertEqual(lst, []) From fa0dea3a516095459bd217ae1f80f2faef4a19e9 Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Sun, 8 Nov 2026 20:49:24 +0100 Subject: [PATCH 3/3] Add What's New and Changelog entries --- Doc/whatsnew/3.16.rst | 4 ++++ .../next/C_API/2026-11-08-20-49-23.gh-issue-161635.iJAyGe.rst | 3 +++ 2 files changed, 7 insertions(+) create mode 100644 Misc/NEWS.d/next/C_API/2026-11-08-20-49-23.gh-issue-161635.iJAyGe.rst diff --git a/Doc/whatsnew/3.16.rst b/Doc/whatsnew/3.16.rst index 4af5d3c0bd072e2..4ae0dbd0f92d55e 100644 --- a/Doc/whatsnew/3.16.rst +++ b/Doc/whatsnew/3.16.rst @@ -1398,6 +1398,10 @@ New features API. (Contributed by Nathan Goldbaum and Victor Stinner in :gh:`158842`.) +* Add :c:func:`PyList_AsTupleAndClear` function: similar to + :c:func:`PyList_AsTuple` but faster, and clear the input list. + (Contributed by Victor Stinner in :gh:`161635`.) + * Add the :ref:`PyUnicodeWriter API ` to the limited C API. (Contributed by Victor Stinner in :gh:`161172`.) diff --git a/Misc/NEWS.d/next/C_API/2026-11-08-20-49-23.gh-issue-161635.iJAyGe.rst b/Misc/NEWS.d/next/C_API/2026-11-08-20-49-23.gh-issue-161635.iJAyGe.rst new file mode 100644 index 000000000000000..a117ce96b79c6d8 --- /dev/null +++ b/Misc/NEWS.d/next/C_API/2026-11-08-20-49-23.gh-issue-161635.iJAyGe.rst @@ -0,0 +1,3 @@ +Add :c:func:`PyList_AsTupleAndClear` function: similar to +:c:func:`PyList_AsTuple` but faster, and clear the input list. Patch by +Victor Stinner.