Abort array/tensor construction if pyobject is not valid#176
Abort array/tensor construction if pyobject is not valid#176JohanMabille merged 1 commit intoxtensor-stack:masterfrom
Conversation
|
Thanks for tackling this! I think we should mimic the behavior of pybind11 / python and throw an exception in the constructor if the argument type mismatches, as you propose as an alternative. Aborting the execution of EDIT: also I think it could be nice to add a test for this use case so we are notified in the future if we break this behavior. |
|
In fact, pybind11 does not expect an exception if the cast fails: the caster should just returns false. So from the point of view of pybind there is absolutely no problem and the incomplete If we throw an exception from the The other solution is to move away from the current optimistic approach of the caster by checking if the |
|
Ok so we have two things here: the behavior of a call from Python with the wrong argument type, and the behavior of the constructor of Regarding the pure C++ behavior, having a segmentation fault due to an invalid initialization is fine, it is expected that you can shoot yourself in the foot if you're not careful enough. Regarding the Python behavior, what I meant with "mimic pybind11 behavior" is having the same behavior as you explain in #174: calling a function expecting a
I don't recall all the internal of pybindd11, thus my proposal of throwing from the constructor since we already check if the type is compatible. |
|
So the current fix is compliant with what you describe:
However, raising an exception from the c++ code without catching it before returning to pybind11 in the type caster would be an error as it would break pybind11 overload resolution mechanism. Note that the Thus, I think that it's a matter of style preference: personally I don't like to throw exceptions from constructors, but I can change the PR in that way if you prefer. |
|
Ok, thanks for the clarification and all the details. I have the same preference as you regarding throwing exceptions form constructors, I thought it was the only way to get the same behavior as pybind11 (as I said previously, I don't remember all the internal of pybind11). |
This PR fixes #174.
Currently when pybind11 tries to cast a
pyobject, that is not compatible with the ndarray interface, into apyarray(or apytensor), the custom type caster ends up building apyarraybased on an invalidpyobject(pointing tonull). This leads to a segfault wheninit_from_pythonis called in the contructor.The proposed solution is to abort the function
init_from_pythonif the underlyingpyobjectis invalid.Note that the constructed
pyarrayobject will itself be invalid, which is consistent with the base classpyobjectbut probably not with thextensorusual behavior. Another possibility could be to throw an exception or to change the validation logic of the type caster.