[Mlir-commits] [mlir] d964190 - [MLIR][Python] Don't throw in PyDenseArrayIterator dunderNext (#218193)
llvmlistbot at llvm.org
llvmlistbot at llvm.org
Sat Aug 22 22:55:22 PDT 2026
Author: Maksim Levental
Date: 2026-08-22T22:55:18-07:00
New Revision: d9641906f295fc1c3d5b540dcc35c5dcab3e0de0
URL: https://github.com/llvm/llvm-project/commit/d9641906f295fc1c3d5b540dcc35c5dcab3e0de0
DIFF: https://github.com/llvm/llvm-project/commit/d9641906f295fc1c3d5b540dcc35c5dcab3e0de0.diff
LOG: [MLIR][Python] Don't throw in PyDenseArrayIterator dunderNext (#218193)
`PyDenseArrayIterator::dunderNext` signaled iterator exhaustion by
throwing `nanobind::stop_iteration()`. Raising a C++ exception to signal
`StopIteration` incurs stack-unwinding cost on every loop over a dense
array attribute.
#175377 replaced this pattern with `PyErr_SetNone(PyExc_StopIteration)`
(return a null object after setting the Python error indicator) for the
other iterators in the bindings. `PyDenseArrayIterator` was missed in
that change and still throws. This PR applies the same conversion to
`PyDenseArrayIterator::dunderNext`.
Assisted by: Claude
Added:
Modified:
mlir/include/mlir/Bindings/Python/IRAttributes.h
Removed:
################################################################################
diff --git a/mlir/include/mlir/Bindings/Python/IRAttributes.h b/mlir/include/mlir/Bindings/Python/IRAttributes.h
index fcc003ab365fa..fbebea40f1ac8 100644
--- a/mlir/include/mlir/Bindings/Python/IRAttributes.h
+++ b/mlir/include/mlir/Bindings/Python/IRAttributes.h
@@ -131,11 +131,16 @@ class MLIR_PYTHON_API_EXPORTED PyDenseArrayAttribute
PyDenseArrayIterator dunderIter() { return *this; }
/// Return the next element.
- EltTy dunderNext() {
- // Throw if the index has reached the end.
- if (nextIndex >= mlirDenseArrayGetNumElements(attr.get()))
- throw nanobind::stop_iteration();
- return DerivedT::getElement(attr.get(), nextIndex++);
+ nanobind::typed<nanobind::object, EltTy> dunderNext() {
+ // Set StopIteration if the index has reached the end. Signaling
+ // exhaustion via the Python error indicator rather than a C++ exception
+ // avoids the cost of stack unwinding on every iteration.
+ if (nextIndex >= mlirDenseArrayGetNumElements(attr.get())) {
+ PyErr_SetNone(PyExc_StopIteration);
+ // python functions should return NULL after setting any exception
+ return nanobind::object();
+ }
+ return nanobind::cast(DerivedT::getElement(attr.get(), nextIndex++));
}
/// Bind the iterator class.
More information about the Mlir-commits
mailing list