From 220c9466be7d24589984f89abfa4b25c203bb2a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Lam?= Date: Tue, 5 May 2020 14:42:57 +0200 Subject: [PATCH] py: Fix default value handling in Map.get() Any type for the default value should be allowed. --- py/pybind11_common.h | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/py/pybind11_common.h b/py/pybind11_common.h index 0e5817e..1d5c4c3 100644 --- a/py/pybind11_common.h +++ b/py/pybind11_common.h @@ -144,11 +144,15 @@ py::class_ BindMap(py::handle scope, const std::string& name, .def("clear", &Map::clear) .def( "get", - [](const Map& map, const Key& key, const std::optional& value) { + [](const Map& map, const Key& key, + std::optional default_value) -> std::variant { const auto it = map.find(key); - if (it == map.cend()) - return value; - return std::make_optional(it->second); + if (it == map.cend()) { + if (default_value) + return *default_value; + throw py::key_error(); + } + return it->second; }, py::return_value_policy::reference_internal, "key"_a, "default"_a = std::nullopt) .def(