Skip to content

Add get method to py::dict #1513

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
8 changes: 8 additions & 0 deletions include/pybind11/pytypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -1173,6 +1173,14 @@ class dict : public object {
void clear() const { PyDict_Clear(ptr()); }
bool contains(handle key) const { return PyDict_Contains(ptr(), key.ptr()) == 1; }
bool contains(const char *key) const { return PyDict_Contains(ptr(), pybind11::str(key).ptr()) == 1; }
template <typename T> object get(handle key, T &&defaultv) const {
PyObject* ret = PyDict_GetItem(ptr(), key.ptr());
return reinterpret_borrow<object>(ret ? handle(ret) : detail::object_or_cast(std::forward<T>(defaultv)));
}
template <typename T> object get(const char *key, T &&defaultv) const {
PyObject* ret = PyDict_GetItemString(ptr(), key);
return reinterpret_borrow<object>(ret ? handle(ret) : detail::object_or_cast(std::forward<T>(defaultv)));
}

private:
/// Call the `dict` Python type -- always returns a new reference
Expand Down
4 changes: 4 additions & 0 deletions tests/test_pytypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ TEST_SUBMODULE(pytypes, m) {
auto d2 = py::dict("z"_a=3, **d1);
return d2;
});
m.def("dict_get_test", []() {
py::dict d("key"_a=1);
return py::make_tuple(d.get("key", 2), d.get("key2", 3));
});

// test_str
m.def("str_from_string", []() { return py::str(std::string("baz")); });
Expand Down
1 change: 1 addition & 0 deletions tests/test_pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ def test_dict(capture, doc):

assert m.dict_keyword_constructor() == {"x": 1, "y": 2, "z": 3}

assert m.dict_get_test() == (1, 3)

def test_str(doc):
assert m.str_from_string().encode().decode() == "baz"
Expand Down