Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add list.clear() in the C++ API. #30120

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions include/pybind11/pytypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -2195,6 +2195,7 @@ class list : public object {
throw error_already_set();
}
}
void clear() { PyList_SetSlice(m_ptr, 0, PyList_Size(m_ptr), nullptr); }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The return value of PyList_SetSlice() needs to be checked, and you need to add throw error_already_set(); if it is not 0:

https://docs.python.org/3/c-api/list.html#c.PyList_SetSlice

(I think it's fine/best to omit a similar check for PyList_Size(): from the context we're sure that m_ptr is a Python list object.)

};

class args : public tuple {
Expand Down
1 change: 1 addition & 0 deletions tests/test_pytypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
2 changes: 2 additions & 0 deletions tests/test_pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading