Skip to content
Merged
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
30 changes: 30 additions & 0 deletions include/pybind11/pytypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -944,6 +944,22 @@ inline PyObject *dict_getitemstringref(PyObject *v, const char *key) {
#endif
}

// PyDict_GetItemRef was added in Python 3.13.0a1 (limited API: 3.13).
inline PyObject *dict_getitemref(PyObject *v, PyObject *key) {
#if (defined(Py_LIMITED_API) && Py_LIMITED_API + 0 >= 0x030D0000) \
|| (!defined(Py_LIMITED_API) && PY_VERSION_HEX >= 0x030D00A1)
PyObject *rv = nullptr;
if (PyDict_GetItemRef(v, key, &rv) < 0) {
throw error_already_set();
}
return rv;
#else
PyObject *rv = dict_getitem(v, key);
Py_XINCREF(rv);
return rv;
#endif
}

// Returns a borrowed reference (the dict holds the value).
inline PyObject *dict_setdefaultstring(PyObject *v, const char *key, PyObject *defaultobj) {
PyObject *kv = PyUnicode_FromString(key);
Expand Down Expand Up @@ -2174,6 +2190,20 @@ class dict : public object {
}
return result == 1;
}
/// Equivalent to Python's ``dict.get(key, default)``: one lookup, no ``KeyError``.
template <typename K, typename D>
object get(K &&key, D &&default_) const {
PyObject *rv
= detail::dict_getitemref(m_ptr, detail::object_or_cast(std::forward<K>(key)).ptr());
if (rv != nullptr) {
return reinterpret_steal<object>(rv);
}
return reinterpret_borrow<object>(detail::object_or_cast(std::forward<D>(default_)).ptr());
}
template <typename K>
object get(K &&key) const {
return get(std::forward<K>(key), none());
}

private:
/// Call the `dict` Python type -- always returns a new reference
Expand Down
5 changes: 5 additions & 0 deletions tests/test_pytypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,11 @@ TEST_SUBMODULE(pytypes, m) {
[](const py::dict &dict, const py::object &val) { return dict.contains(val); });
m.def("dict_contains",
[](const py::dict &dict, const char *val) { return dict.contains(val); });
m.def("dict_get", [](const py::dict &dict, const py::object &key) { return dict.get(key); });
m.def("dict_get", [](const py::dict &dict, const py::object &key, const py::object &def) {
return dict.get(key, def);
});
m.def("dict_get_cast", [](const py::dict &dict) { return dict.get("foo", 42); });

// test_tuple
m.def("tuple_no_args", []() { return py::tuple{}; });
Expand Down
9 changes: 9 additions & 0 deletions tests/test_pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,15 @@ def test_dict(capture, doc):
assert m.dict_contains({42: None}, 42)
assert m.dict_contains({"foo": None}, "foo")

assert m.dict_get({42: "x"}, 42) == "x"
assert m.dict_get({}, 42) is None
assert m.dict_get({42: None}, 42, "default") is None
assert m.dict_get({}, 42, "default") == "default"
assert m.dict_get_cast({"foo": "bar"}) == "bar"
assert m.dict_get_cast({}) == 42
with pytest.raises(TypeError, match="unhashable"):
m.dict_get({}, [])

assert doc(m.get_dict) == "get_dict() -> dict"
assert doc(m.print_dict) == "print_dict(arg0: dict) -> None"

Expand Down
Loading