diff --git a/include/pybind11/pytypes.h b/include/pybind11/pytypes.h index adf512cc23..73a37edd9a 100644 --- a/include/pybind11/pytypes.h +++ b/include/pybind11/pytypes.h @@ -113,6 +113,13 @@ class object_api : public pyobject_tag { 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; + /// See above (the key is any other C++ type; it is converted with `pybind11::cast`) + template , + std::is_convertible, + std::is_convertible>::value, + int> = 0> + item_accessor operator[](T &&key) const; /** \rst Return an internal functor to access the object's attributes. Casting the @@ -2546,6 +2553,15 @@ item_accessor object_api::operator[](const char *key) const { return {derived(), pybind11::str(key)}; } template +template , + std::is_convertible, + std::is_convertible>::value, + int>> +item_accessor object_api::operator[](T &&key) const { + return {derived(), object_or_cast(std::forward(key))}; +} +template obj_attr_accessor object_api::attr(handle key) const { return {derived(), reinterpret_borrow(key)}; } diff --git a/tests/test_pytypes.cpp b/tests/test_pytypes.cpp index afa344536f..434078d209 100644 --- a/tests/test_pytypes.cpp +++ b/tests/test_pytypes.cpp @@ -448,6 +448,22 @@ TEST_SUBMODULE(pytypes, m) { return d; }); + // Issue #1309: any castable C++ type is a valid key + m.def("accessor_cast_key", [](const py::object &o) { + py::object d = py::dict(); + d[1] = "int"; + d[0] = "zero"; + d[2.5] = "float"; + d[std::string("s")] = "string"; + d[std::make_pair(1, 2)] = "pair"; + d["count"] = py::len(d); + d["read"] = py::object(d[1]); + d["nested"] = py::object(o[1][2]); + d["via_accessor"] = py::object(o.attr("__getitem__")(1)[0]); + d["list_object_key"] = py::object(py::list(o)[py::int_(0)][1]); + return d; + }); + m.def("tuple_accessor", [](const py::tuple &existing_t) { try { existing_t[0] = 1; diff --git a/tests/test_pytypes.py b/tests/test_pytypes.py index 7e419b98e0..911be0b70a 100644 --- a/tests/test_pytypes.py +++ b/tests/test_pytypes.py @@ -434,6 +434,19 @@ def func(self, x, *args): assert d["implicit_list"] == [1, 2, 3] assert all(x in TestObject.__dict__ for x in d["implicit_dict"]) + assert m.accessor_cast_key(((1, 2, 3), (4, 5, 6))) == { + 1: "int", + 0: "zero", + 2.5: "float", + "s": "string", + (1, 2): "pair", + "count": 5, + "read": "int", + "nested": 6, + "via_accessor": 4, + "list_object_key": 2, + } + assert m.tuple_accessor(()) == (0, 1, 2) d = m.accessor_assignment()