diff --git a/include/pybind11/pytypes.h b/include/pybind11/pytypes.h index a27d6aed09..3d2d0c2dac 100644 --- a/include/pybind11/pytypes.h +++ b/include/pybind11/pytypes.h @@ -2183,6 +2183,11 @@ class list : public object { throw error_already_set(); } } + void clear() /* py-non-const */ { + if (PyList_SetSlice(m_ptr, 0, PyList_Size(m_ptr), nullptr) == -1) { + throw error_already_set(); + } + } }; class args : public tuple { diff --git a/tests/test_pytypes.cpp b/tests/test_pytypes.cpp index 12e6151812..f3709d40c6 100644 --- a/tests/test_pytypes.cpp +++ b/tests/test_pytypes.cpp @@ -135,6 +135,7 @@ TEST_SUBMODULE(pytypes, m) { m.def("list_size_t", []() { return py::list{(py::size_t) 0}; }); m.def("list_insert_ssize_t", [](py::list *l) { return l->insert((py::ssize_t) 1, 83); }); m.def("list_insert_size_t", [](py::list *l) { return l->insert((py::size_t) 3, 57); }); + m.def("list_clear", [](py::list *l) { l->clear(); }); m.def("get_list", []() { py::list list; list.append("value"); diff --git a/tests/test_pytypes.py b/tests/test_pytypes.py index d215b4e8a6..38edfd9998 100644 --- a/tests/test_pytypes.py +++ b/tests/test_pytypes.py @@ -65,6 +65,8 @@ def test_list(capture, doc): assert lins == [1, 83, 2] m.list_insert_size_t(lins) assert lins == [1, 83, 2, 57] + m.list_clear(lins) + assert lins == [] with capture: lst = m.get_list()