[all-commits] [llvm/llvm-project] 2a5d49: [mlir][python] Add __{bool, float, int, str}__ to bin...

Ingo Müller via All-commits all-commits at lists.llvm.org
Tue Aug 29 07:53:42 PDT 2023

  Branch: refs/heads/main
  Home:   https://github.com/llvm/llvm-project
  Commit: 2a5d497494c24425e99655b85e2277dd3f15a400
  Author: Ingo Müller <ingomueller at google.com>
  Date:   2023-08-29 (Tue, 29 Aug 2023)

  Changed paths:
    M mlir/lib/Bindings/Python/IRAttributes.cpp
    M mlir/test/python/ir/attributes.py

  Log Message:
  [mlir][python] Add __{bool,float,int,str}__ to bindings of attributes.

This allows to use Python's `bool(.)`, `float(.)`, `int(.)`, and
`str(.)` to convert pybound attributes to the corresponding native
Python types. In particular, pybind11 uses these functions to
automatically cast objects to the corresponding primitive types wherever
they are required by pybound functions, e.g., arguments are converted to
Python's `int` if the C++ signature requires a C++ `int`. With this
patch, pybound attributes can by used wherever the corresponding native
types are expected. New tests show-case this behavior in the
constructors of `Dense*ArrayAttr`.

Note that this changes the output of Python's `str` on `StringAttr` from
`"hello"` to `hello`. Arguably, this is still in line with `str`s goal
of producing a readable interpretation of the value, even if it is now
not unambiously a string anymore (`print(ir.Attribute.parse('"42"'))`
now outputs `42`). However, this is consistent with instances of
Python's `str` (`print("42")` outputs `42`), and `repr` still provides
an unambigous representation if one is required.

Reviewed By: springerm

Differential Revision: https://reviews.llvm.org/D158974

More information about the All-commits mailing list