Skip to content

Commit

Permalink
Fix #5399: iterator increment operator does not skip first item
Browse files Browse the repository at this point in the history
  • Loading branch information
dalboris committed Oct 8, 2024
1 parent c4a05f9 commit 0c47225
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 5 deletions.
16 changes: 11 additions & 5 deletions include/pybind11/pytypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -1470,27 +1470,26 @@ class iterator : public object {
PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check)

iterator &operator++() {
init();
advance();
return *this;
}

iterator operator++(int) {
auto rv = *this;
init();
advance();
return rv;
}

// NOLINTNEXTLINE(readability-const-return-type) // PR #3263
reference operator*() const {
if (m_ptr && !value.ptr()) {
auto &self = const_cast<iterator &>(*this);
self.advance();
}
init();
return value;
}

pointer operator->() const {
operator*();
init();
return &value;
}

Expand All @@ -1513,6 +1512,13 @@ class iterator : public object {
friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); }

private:
void init() const {
if (m_ptr && !value.ptr()) {
auto &self = const_cast<iterator &>(*this);
self.advance();
}
}

void advance() {
value = reinterpret_steal<object>(PyIter_Next(m_ptr));
if (value.ptr() == nullptr && PyErr_Occurred()) {
Expand Down
5 changes: 5 additions & 0 deletions tests/test_pytypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,11 @@ TEST_SUBMODULE(pytypes, m) {
m.def("get_iterator", [] { return py::iterator(); });
// test_iterable
m.def("get_iterable", [] { return py::iterable(); });
m.def("get_second_item_from_iterable", [](const py::iterable &iter) {
py::iterator it = iter.begin();
++it;
return *it;
});
m.def("get_frozenset_from_iterable",
[](const py::iterable &iter) { return py::frozenset(iter); });
m.def("get_list_from_iterable", [](const py::iterable &iter) { return py::list(iter); });
Expand Down
6 changes: 6 additions & 0 deletions tests/test_pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ def test_iterable(doc):
assert doc(m.get_iterable) == "get_iterable() -> Iterable"


def test_get_second_item_from_iterable():
lins = [1, 2]
i = m.get_second_item_from_iterable(lins)
assert i == 2


def test_float(doc):
assert doc(m.get_float) == "get_float() -> float"

Expand Down

0 comments on commit 0c47225

Please sign in to comment.