Skip to content
Open
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
16 changes: 16 additions & 0 deletions include/pybind11/pytypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 <typename T,
enable_if_t<none_of<is_pyobject<T>,
std::is_convertible<T, handle>,
std::is_convertible<T, const char *>>::value,
int> = 0>
item_accessor operator[](T &&key) const;

/** \rst
Return an internal functor to access the object's attributes. Casting the
Expand Down Expand Up @@ -2546,6 +2553,15 @@ item_accessor object_api<D>::operator[](const char *key) const {
return {derived(), pybind11::str(key)};
}
template <typename D>
template <typename T,
enable_if_t<none_of<is_pyobject<T>,
std::is_convertible<T, handle>,
std::is_convertible<T, const char *>>::value,
int>>
item_accessor object_api<D>::operator[](T &&key) const {
return {derived(), object_or_cast(std::forward<T>(key))};
}
template <typename D>
obj_attr_accessor object_api<D>::attr(handle key) const {
return {derived(), reinterpret_borrow<object>(key)};
}
Expand Down
16 changes: 16 additions & 0 deletions tests/test_pytypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
13 changes: 13 additions & 0 deletions tests/test_pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading