From a259c94847be56cc14747b4362d23f4cb56fd2b6 Mon Sep 17 00:00:00 2001 From: Henry Schreiner Date: Fri, 13 Nov 2026 10:15:27 -0500 Subject: [PATCH] feat: add dict::get Mirror Python's dict.get(key, default=None) with a single lookup. Assisted-by: ClaudeCode:claude-fable-5-2 --- include/pybind11/pytypes.h | 30 ++++++++++++++++++++++++++++++ tests/test_pytypes.cpp | 5 +++++ tests/test_pytypes.py | 9 +++++++++ 3 files changed, 44 insertions(+) diff --git a/include/pybind11/pytypes.h b/include/pybind11/pytypes.h index adf512cc23..04b2853646 100644 --- a/include/pybind11/pytypes.h +++ b/include/pybind11/pytypes.h @@ -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); @@ -2174,6 +2190,20 @@ class dict : public object { } return result == 1; } + /// Equivalent to Python's ``dict.get(key, default)``: one lookup, no ``KeyError``. + template + object get(K &&key, D &&default_) const { + PyObject *rv + = detail::dict_getitemref(m_ptr, detail::object_or_cast(std::forward(key)).ptr()); + if (rv != nullptr) { + return reinterpret_steal(rv); + } + return reinterpret_borrow(detail::object_or_cast(std::forward(default_)).ptr()); + } + template + object get(K &&key) const { + return get(std::forward(key), none()); + } private: /// Call the `dict` Python type -- always returns a new reference diff --git a/tests/test_pytypes.cpp b/tests/test_pytypes.cpp index afa344536f..2d3f57d909 100644 --- a/tests/test_pytypes.cpp +++ b/tests/test_pytypes.cpp @@ -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{}; }); diff --git a/tests/test_pytypes.py b/tests/test_pytypes.py index 7e419b98e0..2c11dd76ba 100644 --- a/tests/test_pytypes.py +++ b/tests/test_pytypes.py @@ -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"