Added __contains__ to stl bindings for maps (#1767)
* Added __contains__ to stl bindings for maps
diff --git a/include/pybind11/stl_bind.h b/include/pybind11/stl_bind.h
index 38dd68f..d6f4c63 100644
--- a/include/pybind11/stl_bind.h
+++ b/include/pybind11/stl_bind.h
@@ -579,6 +579,15 @@
return_value_policy::reference_internal // ref + keepalive
);
+ cl.def("__contains__",
+ [](Map &m, const KeyType &k) -> bool {
+ auto it = m.find(k);
+ if (it == m.end())
+ return false;
+ return true;
+ }
+ );
+
// Assignment provided only if the type is copyable
detail::map_assignment<Map, Class_>(cl);
diff --git a/tests/test_stl.py b/tests/test_stl.py
index bf185d5..2335cb9 100644
--- a/tests/test_stl.py
+++ b/tests/test_stl.py
@@ -56,7 +56,9 @@
"""std::map <-> dict"""
d = m.cast_map()
assert d == {"key": "value"}
+ assert "key" in d
d["key2"] = "value2"
+ assert "key2" in d
assert m.load_map(d)
assert doc(m.cast_map) == "cast_map() -> Dict[str, str]"