diff --git a/include/pybind11/pytypes.h b/include/pybind11/pytypes.h index f9625e77e..f7a8600e3 100644 --- a/include/pybind11/pytypes.h +++ b/include/pybind11/pytypes.h @@ -92,11 +92,8 @@ public: subclass causes a corresponding call to ``__getitem__``. Assigning a `handle` or `object` subclass causes a call to ``__setitem__``. \endrst */ - item_accessor operator[](handle key) const; - /// See above (the only difference is that the key's reference is stolen) - item_accessor operator[](object &&key) const; - /// See above (the only difference is that the key is provided as a string literal) - item_accessor operator[](const char *key) const; + template + item_accessor operator[](T &&key) const; /** \rst Return an internal functor to access the object's attributes. Casting the @@ -2270,16 +2267,9 @@ iterator object_api::end() const { return iterator::sentinel(); } template -item_accessor object_api::operator[](handle key) const { - return {derived(), reinterpret_borrow(key)}; -} -template -item_accessor object_api::operator[](object &&key) const { - return {derived(), std::move(key)}; -} -template -item_accessor object_api::operator[](const char *key) const { - return {derived(), pybind11::str(key)}; +template +item_accessor object_api::operator[](T &&key) const { + return {derived(), reinterpret_borrow(detail::object_or_cast(std::forward(key)))}; } template obj_attr_accessor object_api::attr(handle key) const { diff --git a/tests/test_pytypes.cpp b/tests/test_pytypes.cpp index cb81007c3..ef937db2f 100644 --- a/tests/test_pytypes.cpp +++ b/tests/test_pytypes.cpp @@ -126,6 +126,10 @@ TEST_SUBMODULE(pytypes, m) { m.def("tuple_ssize_t", []() { return py::tuple{(py::ssize_t) 0}; }); m.def("tuple_size_t", []() { return py::tuple{(py::size_t) 0}; }); m.def("get_tuple", []() { return py::make_tuple(42, py::none(), "spam"); }); + m.def("access_tuple_with_int_index", []() { + py::object tpl = py::make_tuple(1, 2); + return tpl[1]; + }); // test_simple_namespace m.def("get_simple_namespace", []() { diff --git a/tests/test_pytypes.py b/tests/test_pytypes.py index 3e9d51a27..4c5d81319 100644 --- a/tests/test_pytypes.py +++ b/tests/test_pytypes.py @@ -152,6 +152,7 @@ def test_tuple(): assert m.tuple_ssize_t() == () assert m.tuple_size_t() == () assert m.get_tuple() == (42, None, "spam") + assert m.access_tuple_with_int_index() == (2) def test_simple_namespace():