diff --git a/include/pybind11/numpy.h b/include/pybind11/numpy.h index f8ce14ebf..ea6454254 100644 --- a/include/pybind11/numpy.h +++ b/include/pybind11/numpy.h @@ -702,8 +702,10 @@ protected: /// Create array from any object -- always returns a new reference static PyObject *raw_array(PyObject *ptr, int ExtraFlags = 0) { - if (ptr == nullptr) + if (ptr == nullptr) { + PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array from a nullptr"); return nullptr; + } return detail::npy_api::get().PyArray_FromAny_( ptr, nullptr, 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr); } @@ -808,8 +810,10 @@ public: protected: /// Create array from any object -- always returns a new reference static PyObject *raw_array_t(PyObject *ptr) { - if (ptr == nullptr) + if (ptr == nullptr) { + PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array_t from a nullptr"); return nullptr; + } return detail::npy_api::get().PyArray_FromAny_( ptr, dtype::of().release().ptr(), 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr); diff --git a/tests/test_numpy_array.cpp b/tests/test_numpy_array.cpp index cd6487249..0b547041d 100644 --- a/tests/test_numpy_array.cpp +++ b/tests/test_numpy_array.cpp @@ -264,4 +264,8 @@ test_initializer numpy_array([](py::module &m) { sm.def("array_auxiliaries2", [](py::array_t a) { return auxiliaries(a, a); }); + + // Issue #785: Uninformative "Unknown internal error" exception when constructing array from empty object: + sm.def("array_fail_test", []() { return py::array(py::object()); }); + sm.def("array_t_fail_test", []() { return py::array_t(py::object()); }); }); diff --git a/tests/test_numpy_array.py b/tests/test_numpy_array.py index 14c25b371..6281fa478 100644 --- a/tests/test_numpy_array.py +++ b/tests/test_numpy_array.py @@ -377,3 +377,15 @@ def test_array_unchecked_dyn_dims(msg): assert proxy_auxiliaries2_dyn(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32] assert proxy_auxiliaries2_dyn(z1) == array_auxiliaries2(z1) + + +def test_array_failure(): + from pybind11_tests.array import array_fail_test, array_t_fail_test + + with pytest.raises(ValueError) as excinfo: + array_fail_test() + assert str(excinfo.value) == 'cannot create a pybind11::array from a nullptr' + + with pytest.raises(ValueError) as excinfo: + array_t_fail_test() + assert str(excinfo.value) == 'cannot create a pybind11::array_t from a nullptr'