[Python] Avoid hack in setting __reduce__
attribute of CPPInstance
#19222
+29
−27
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The CPPIntance type is immutable, and new attributes can't be set:
import cppyy >>> setattr(cppyy._backend.CPPInstance, "test", 10) Traceback (most recent call last): File "<python-input-3>", line 1, in <module> setattr(cppyy._backend.CPPInstance, "test", 10) ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: cannot set 'test' attribute of immutable type 'cppyy.CPPInstance' >>>
In our pythonizations, we still want to monkey-patch a
__reduce__
method anyway, and to make Python not complain we to a hack by setting the attribute with the C Python API usingPyObject_GenericSetAttr
. This function doesn't normally do any safety checks, and our monkey patching works.However, the Python debug build is not having any of that, thanks to a new assert that was added a year ago:
https://github.com/python/cpython/blame/c419af9e277bea7dd78f4defefc752fe93b0b8ec/Objects/object.c#L1921
To make the ROOT Python interface work with debug builds of the Python interpreter, we therefore have to implement adding the reduce method properly.
This commit suggests to achieve this by defining the
__reduce__
method in the immutable CPPInstance type within CPyCppyy, but in such a way that its implementation can be routed to ROOT via a private API.