xtensor-stack / xtensor-python

Python bindings for xtensor
BSD 3-Clause "New" or "Revised" License
347 stars 58 forks source link

Optional debug assertion: check that NumPy was imported #259

Closed tdegeus closed 2 years ago

serge-sans-paille commented 3 years ago

I think the general approach is correct. One should probably add the assert in the prelude of each function calling PyArray*. You should use PyRun_SimpleString instead of PyRunStrin.

tdegeus commented 3 years ago

@serge-sans-paille The second comment did indeed the trick. As to your first comment, I don't think I understood you ;)

tdegeus commented 3 years ago

So the implementation essentially works, except for when another exception is raised.

In the CI example:

import xtensor_python_test as xt
xt.simple_array([1, 2, 3])

works fine if xt::import_numpy() was used, and throws of xt::numpy_imported() otherwise.

However,

import xtensor_python_test as xt
xt.simple_array("foo")

that is supposed to throw because on an incorrect input type, now throws incorrectly on xt::numpy_imported() no matter if xt::import_numpy() was used or not. Debugging (see latest CI) shows that in this case xt::numpy_imported() is called twice, whereby

PyRun_SimpleString("__import__('sys').modules['numpy.core']")

correctly returns 0 the first time, but incorrectly returns -1 the second time. So I don't understand this, not do I understand how to work around it. Do you have any idea?

@serge-sans-paille

serge-sans-paille commented 3 years ago

@tdegeus no idea without a debugger attached, and I don't have the time to do that right now :-/