Use `bytes`, not `str`, to return C++ strings to Python.
authorChris Jones <cjfj@deepmind.com>
Thu, 13 Apr 2023 15:05:26 +0000 (17:05 +0200)
committerAlex Zinenko <zinenko@google.com>
Thu, 13 Apr 2023 15:09:19 +0000 (17:09 +0200)
`str` must be valid UTF-8, which is not guaranteed for C++ strings.

Reviewed By: ftynse

Differential Revision: https://reviews.llvm.org/D147818

mlir/lib/Bindings/Python/IRAttributes.cpp
mlir/test/python/ir/attributes.py
mlir/test/python/ir/operation.py

index d252044..4a43ffb 100644 (file)
@@ -490,9 +490,9 @@ public:
         "data",
         [](PyOpaqueAttribute &self) {
           MlirStringRef stringRef = mlirOpaqueAttrGetData(self);
-          return py::str(stringRef.data, stringRef.length);
+          return py::bytes(stringRef.data, stringRef.length);
         },
-        "Returns the data for the Opaqued attributes as a string");
+        "Returns the data for the Opaqued attributes as `bytes`");
   }
 };
 
@@ -528,6 +528,13 @@ public:
           return py::str(stringRef.data, stringRef.length);
         },
         "Returns the value of the string attribute");
+    c.def_property_readonly(
+        "value_bytes",
+        [](PyStringAttribute &self) {
+          MlirStringRef stringRef = mlirStringAttrGetValue(self);
+          return py::bytes(stringRef.data, stringRef.length);
+        },
+        "Returns the value of the string attribute as `bytes`");
   }
 };
 
index 1e1589d..6aad943 100644 (file)
@@ -248,7 +248,7 @@ def testOpaqueAttr():
     oattr = OpaqueAttr(Attribute.parse("#pytest_dummy.dummyattr<>"))
     # CHECK: oattr value: pytest_dummy
     print("oattr value:", oattr.dialect_namespace)
-    # CHECK: oattr value: dummyattr<>
+    # CHECK: oattr value: b'dummyattr<>'
     print("oattr value:", oattr.data)
 
     # Test factory methods.
@@ -265,6 +265,8 @@ def testStringAttr():
     sattr = StringAttr(Attribute.parse('"stringattr"'))
     # CHECK: sattr value: stringattr
     print("sattr value:", sattr.value)
+    # CHECK: sattr value: b'stringattr'
+    print("sattr value:", sattr.value_bytes)
 
     # Test factory methods.
     # CHECK: default_get: "foobar"
index 941420e..2088e16 100644 (file)
@@ -516,6 +516,8 @@ def testOperationAttributes():
   print(f"Attribute type {fattr.type}, value {fattr.value}")
   # CHECK: Attribute value text
   print(f"Attribute value {sattr.value}")
+  # CHECK: Attribute value b'text'
+  print(f"Attribute value {sattr.value_bytes}")
 
   # We don't know in which order the attributes are stored.
   # CHECK-DAG: NamedAttribute(dependent="text")