Skip to content

Commit 35ff42b

Browse files
TCKnetrwgk
andauthored
Add a pybind function to clear a list. (#5153)
* Add a pybing function to clear a list. * Add required error handling. * Add `/* py-non-const */` as suggested by @Skylion007 --------- Co-authored-by: Ralf W. Grosse-Kunstleve <[email protected]>
1 parent 9b3a200 commit 35ff42b

File tree

3 files changed

+8
-0
lines changed

3 files changed

+8
-0
lines changed

include/pybind11/pytypes.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2183,6 +2183,11 @@ class list : public object {
21832183
throw error_already_set();
21842184
}
21852185
}
2186+
void clear() /* py-non-const */ {
2187+
if (PyList_SetSlice(m_ptr, 0, PyList_Size(m_ptr), nullptr) == -1) {
2188+
throw error_already_set();
2189+
}
2190+
}
21862191
};
21872192

21882193
class args : public tuple {

tests/test_pytypes.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ TEST_SUBMODULE(pytypes, m) {
135135
m.def("list_size_t", []() { return py::list{(py::size_t) 0}; });
136136
m.def("list_insert_ssize_t", [](py::list *l) { return l->insert((py::ssize_t) 1, 83); });
137137
m.def("list_insert_size_t", [](py::list *l) { return l->insert((py::size_t) 3, 57); });
138+
m.def("list_clear", [](py::list *l) { l->clear(); });
138139
m.def("get_list", []() {
139140
py::list list;
140141
list.append("value");

tests/test_pytypes.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ def test_list(capture, doc):
6565
assert lins == [1, 83, 2]
6666
m.list_insert_size_t(lins)
6767
assert lins == [1, 83, 2, 57]
68+
m.list_clear(lins)
69+
assert lins == []
6870

6971
with capture:
7072
lst = m.get_list()

0 commit comments

Comments
 (0)