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

Peter Hawkins llvmlistbot at llvm.org
Thu Mar 13 08:56:02 PDT 2025


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

>From 7ea4562389606bd5274d6457816dd7c3999d46d7 Mon Sep 17 00:00:00 2001
From: Peter Hawkins <phawkins at google.com>
Date: Thu, 13 Mar 2025 15:45:43 +0000
Subject: [PATCH] [mlir][python] Small optimization to mlirApiObjectToCapsule.

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.
---
 mlir/include/mlir/Bindings/Python/NanobindAdaptors.h | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/mlir/include/mlir/Bindings/Python/NanobindAdaptors.h b/mlir/include/mlir/Bindings/Python/NanobindAdaptors.h
index 3646bf42e415f..2dd35c097c796 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



More information about the Mlir-commits mailing list