Skip to content

Commit

Permalink
py: Fix default value handling in Map.get()
Browse files Browse the repository at this point in the history
Any type for the default value should be allowed.
  • Loading branch information
leoetlino committed May 5, 2020
1 parent 3ac9083 commit 220c946
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions py/pybind11_common.h
Original file line number Diff line number Diff line change
Expand Up @@ -144,11 +144,15 @@ py::class_<Map, holder_type> BindMap(py::handle scope, const std::string& name,
.def("clear", &Map::clear)
.def(
"get",
[](const Map& map, const Key& key, const std::optional<Value>& value) {
[](const Map& map, const Key& key,
std::optional<py::object> default_value) -> std::variant<py::object, Value> {
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(
Expand Down

0 comments on commit 220c946

Please sign in to comment.