From 12e8774bc9aa4603136f2979088619b495850ca2 Mon Sep 17 00:00:00 2001 From: kingofpayne <43875454+kingofpayne@users.noreply.github.com> Date: Mon, 19 Aug 2019 23:00:36 +0200 Subject: [PATCH] Added support for list insertion. (#1888) --- include/pybind11/pytypes.h | 4 ++++ tests/test_pytypes.cpp | 2 ++ tests/test_pytypes.py | 8 +++++--- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/include/pybind11/pytypes.h b/include/pybind11/pytypes.h index 10f72ccf9..78a604e1d 100644 --- a/include/pybind11/pytypes.h +++ b/include/pybind11/pytypes.h @@ -1265,6 +1265,10 @@ public: template void append(T &&val) const { PyList_Append(m_ptr, detail::object_or_cast(std::forward(val)).ptr()); } + template void insert(size_t index, T &&val) const { + PyList_Insert(m_ptr, static_cast(index), + detail::object_or_cast(std::forward(val)).ptr()); + } }; class args : public tuple { PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check) }; diff --git a/tests/test_pytypes.cpp b/tests/test_pytypes.cpp index a8caca45c..244e1db0d 100644 --- a/tests/test_pytypes.cpp +++ b/tests/test_pytypes.cpp @@ -17,6 +17,8 @@ TEST_SUBMODULE(pytypes, m) { list.append("value"); py::print("Entry at position 0:", list[0]); list[0] = py::str("overwritten"); + list.insert(0, "inserted-0"); + list.insert(2, "inserted-2"); return list; }); m.def("print_list", [](py::list list) { diff --git a/tests/test_pytypes.py b/tests/test_pytypes.py index a0364d6af..0e8d6c33a 100644 --- a/tests/test_pytypes.py +++ b/tests/test_pytypes.py @@ -9,14 +9,16 @@ from pybind11_tests import debug_enabled def test_list(capture, doc): with capture: lst = m.get_list() - assert lst == ["overwritten"] + assert lst == ["inserted-0", "overwritten", "inserted-2"] lst.append("value2") m.print_list(lst) assert capture.unordered == """ Entry at position 0: value - list item 0: overwritten - list item 1: value2 + list item 0: inserted-0 + list item 1: overwritten + list item 2: inserted-2 + list item 3: value2 """ assert doc(m.get_list) == "get_list() -> list"