Skip to content

Commit 244cf89

Browse files
authored
[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.
1 parent 841f463 commit 244cf89

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,14 +46,16 @@ namespace detail {
4646
static nanobind::object mlirApiObjectToCapsule(nanobind::handle apiObject) {
4747
if (PyCapsule_CheckExact(apiObject.ptr()))
4848
return nanobind::borrow<nanobind::object>(apiObject);
49-
if (!nanobind::hasattr(apiObject, MLIR_PYTHON_CAPI_PTR_ATTR)) {
49+
nanobind::object api =
50+
nanobind::getattr(apiObject, MLIR_PYTHON_CAPI_PTR_ATTR, nanobind::none());
51+
if (api.is_none()) {
5052
std::string repr = nanobind::cast<std::string>(nanobind::repr(apiObject));
5153
throw nanobind::type_error(
5254
(llvm::Twine("Expected an MLIR object (got ") + repr + ").")
5355
.str()
5456
.c_str());
5557
}
56-
return apiObject.attr(MLIR_PYTHON_CAPI_PTR_ATTR);
58+
return api;
5759
}
5860

5961
// Note: Currently all of the following support cast from nanobind::object to

0 commit comments

Comments
 (0)