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

llvmlistbot at llvm.org llvmlistbot at llvm.org
Fri Mar 14 08:10:45 PDT 2025


Author: Peter Hawkins
Date: 2025-03-14T08:10:42-07:00
New Revision: 244cf89f143a4fa09494280dba4a49d4cff007f6

URL: https://github.com/llvm/llvm-project/commit/244cf89f143a4fa09494280dba4a49d4cff007f6
DIFF: https://github.com/llvm/llvm-project/commit/244cf89f143a4fa09494280dba4a49d4cff007f6.diff

LOG: [mlir][python] Small optimization to mlirApiObjectToCapsule. (#131160)

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.

Added: 
    

Modified: 
    mlir/include/mlir/Bindings/Python/NanobindAdaptors.h

Removed: 
    


################################################################################
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