This is an archive of the discontinued LLVM Phabricator instance.

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

Authored by ingomueller-net on Aug 28 2023, 3:05 AM.

Details

Summary

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 strs 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.

Diff Detail

Event Timeline

Herald added a project: Restricted Project. · View Herald TranscriptAug 28 2023, 3:05 AM
ingomueller-net requested review of this revision.Aug 28 2023, 3:05 AM
Herald added a project: Restricted Project. · View Herald TranscriptAug 28 2023, 3:05 AM
springerm added inline comments.Aug 28 2023, 6:06 AM
mlir/test/python/ir/attributes.py
298

I'm surprised that this parses at all. What's happening here?

310

Why does this exist?

mlir/test/python/ir/attributes.py
298

Attribute.parse calls a C++ function that parses MLIR assembly. "stringattr" is the assembly of a StringAttr with the value stringattr and the type NoneType. "stringattr" : i32 is the assembly of a StringAttr with the value stringattr and the type i32.

310

typed_get is a method that constructs a StringAttr with the given value and the given type (see above). I can only assume that typed StringAttr are less common than those using NoneType, so the get function does not require a type.

springerm accepted this revision.Aug 29 2023, 7:47 AM
This revision is now accepted and ready to land.Aug 29 2023, 7:47 AM

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.

Is this really true of __str__ as well? That'd be pretty surprising, as pretty much every python object is string-able.

I agree. I'll investigate tomorrow when I am back at work.