[Mlir-commits] [mlir] [mlir][python] Small optimization to mlirApiObjectToCapsule. (PR #131160)

llvmlistbot at llvm.org llvmlistbot at llvm.org
Thu Mar 13 08:49:10 PDT 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-mlir

Author: Peter Hawkins (hawkinsp)

<details>
<summary>Changes</summary>

Call nb::getattr(...) rather than using nb::hasattr() and .attr(). Saves a Python string allocation and a dictionary lookup when using a recent nanobind.

Optimization only, no changes in behavior expected.

---
Full diff: https://github.com/llvm/llvm-project/pull/131160.diff


1 Files Affected:

- (modified) mlir/include/mlir/Bindings/Python/NanobindAdaptors.h (+4-2) 


``````````diff
diff --git a/mlir/include/mlir/Bindings/Python/NanobindAdaptors.h b/mlir/include/mlir/Bindings/Python/NanobindAdaptors.h
index 3646bf42e415f..3d417b2c507cd 100644
--- a/mlir/include/mlir/Bindings/Python/NanobindAdaptors.h
+++ b/mlir/include/mlir/Bindings/Python/NanobindAdaptors.h
@@ -46,14 +46,16 @@ namespace detail {
 static nanobind::object mlirApiObjectToCapsule(nanobind::handle apiObject) {
   if (PyCapsule_CheckExact(apiObject.ptr()))
     return nanobind::borrow<nanobind::object>(apiObject);
-  if (!nanobind::hasattr(apiObject, MLIR_PYTHON_CAPI_PTR_ATTR)) {
+  nanobind::object api = nanobind::getattr(
+      apiObject, MLIR_PYTHON_CAPI_PTR_ATTR, nanobind::none());
+  if (api.is_none()) {
     std::string repr = nanobind::cast<std::string>(nanobind::repr(apiObject));
     throw nanobind::type_error(
         (llvm::Twine("Expected an MLIR object (got ") + repr + ").")
             .str()
             .c_str());
   }
-  return apiObject.attr(MLIR_PYTHON_CAPI_PTR_ATTR);
+  return api;
 }
 
 // Note: Currently all of the following support cast from nanobind::object to

``````````

</details>


https://github.com/llvm/llvm-project/pull/131160


More information about the Mlir-commits mailing list