[Mlir-commits] [mlir] [mlir][python] Define __index__ on PyIntegerAttribute (PR #215555)

llvmlistbot at llvm.org llvmlistbot at llvm.org
Tue Aug 11 06:30:32 PDT 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-mlir

Author: Peter Hawkins (hawkinsp)

<details>
<summary>Changes</summary>

In nanobind v2.14.0+, integer casting from Python objects to C++ integer types was updated to require `__index__` (`PyNumber_Index`) instead of `__int__`.

https://nanobind.readthedocs.io/en/latest/changelog.html#version-2-14-0-aug-7-2026

Because `PyIntegerAttribute` defined `__int__` but not `__index__`, passing `IntegerAttr` instances to bindings expecting integer sequences failed. Specifically, in `mlir/test/python/ir/attributes.py`:

    # CHECK: input: [IntegerAttr(4 : i64), IntegerAttr(2 : i64)] (<class 'list'>),
    # CHECK-SAME: result: array<i8: 4, 2>
    create_and_print(DenseI8ArrayAttr, [Attribute.parse(f"{x}") for x in [4, 2]])

Failed because `DenseI8ArrayAttr.get([IntegerAttr(4 : i64), IntegerAttr(2 : i64)])` raised:

    TypeError: get(): incompatible function arguments. The following argument types are supported:
        1. get(values: collections.abc.Sequence[int], context: _mlir.ir.Context | None = None) -> mlir._mlir_libs._mlir.ir.DenseI8ArrayAttr

Define `__index__` on `PyIntegerAttribute` using `toPyInt` to restore implicit integer conversions for `IntegerAttr`.

Assisted-by: Gemini

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


1 Files Affected:

- (modified) mlir/lib/Bindings/Python/IRAttributes.cpp (+2) 


``````````diff
diff --git a/mlir/lib/Bindings/Python/IRAttributes.cpp b/mlir/lib/Bindings/Python/IRAttributes.cpp
index 7fada5bbc8502..d4a71dd4937a9 100644
--- a/mlir/lib/Bindings/Python/IRAttributes.cpp
+++ b/mlir/lib/Bindings/Python/IRAttributes.cpp
@@ -423,6 +423,8 @@ void PyIntegerAttribute::bindDerived(ClassTy &c) {
   c.def_prop_ro("value", toPyInt, "Returns the value of the integer attribute");
   c.def("__int__", toPyInt,
         "Converts the value of the integer attribute to a Python int");
+  c.def("__index__", toPyInt,
+        "Converts the value of the integer attribute to a Python int");
   c.def_prop_ro_static("static_typeid", [](nb::object & /*class*/) {
     return PyTypeID(mlirIntegerAttrGetTypeID());
   });

``````````

</details>


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


More information about the Mlir-commits mailing list