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(