diff --git a/mlir/lib/Bindings/Python/IRAttributes.cpp b/mlir/lib/Bindings/Python/IRAttributes.cpp --- a/mlir/lib/Bindings/Python/IRAttributes.cpp +++ b/mlir/lib/Bindings/Python/IRAttributes.cpp @@ -698,7 +698,13 @@ intptr_t dunderLen() { return mlirDictionaryAttrGetNumElements(*this); } + bool dunderContains(const std::string &name) { + return !mlirAttributeIsNull( + mlirDictionaryAttrGetElementByName(*this, toMlirStringRef(name))); + } + static void bindDerived(ClassTy &c) { + c.def("__contains__", &PyDictAttribute::dunderContains); c.def("__len__", &PyDictAttribute::dunderLen); c.def_static( "get", diff --git a/mlir/test/python/ir/attributes.py b/mlir/test/python/ir/attributes.py --- a/mlir/test/python/ir/attributes.py +++ b/mlir/test/python/ir/attributes.py @@ -340,6 +340,12 @@ # CHECK: "string" print(a['stringattr']) + # CHECK: True + print('stringattr' in a) + + # CHECK: False + print('not_in_dict' in a) + # Check that exceptions are raised as expected. try: _ = a['does_not_exist']