[llvm-branch-commits] [mlir] 551bf48 - [mlir][python] Define __index__ on PyIntegerAttribute (#215555)

Tobias Hieta via llvm-branch-commits llvm-branch-commits at lists.llvm.org
Sun Nov 15 12:05:51 PST 2026


Author: Peter Hawkins
Date: 2026-11-15T21:05:21+01:00
New Revision: 551bf48cf74f5aa587924a38f2cb29f72e7c9497

URL: https://github.com/llvm/llvm-project/commit/551bf48cf74f5aa587924a38f2cb29f72e7c9497
DIFF: https://github.com/llvm/llvm-project/commit/551bf48cf74f5aa587924a38f2cb29f72e7c9497.diff

LOG: [mlir][python] Define __index__ on PyIntegerAttribute (#215555)

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
(cherry picked from commit 17a2349c06b931d1692e26e98492ff5e1a7035a5)

Added: 
    

Modified: 
    mlir/lib/Bindings/Python/IRAttributes.cpp

Removed: 
    


################################################################################
diff  --git a/mlir/lib/Bindings/Python/IRAttributes.cpp b/mlir/lib/Bindings/Python/IRAttributes.cpp
index 7fada5bbc85029..d4a71dd4937a9a 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());
   });


        


More information about the llvm-branch-commits mailing list