@@ -120,6 +120,26 @@ inline numpy_internals &get_numpy_internals() {
120120 return *ptr;
121121}
122122
123+ module_ import_numpy_core_submodule (const char * submodule_name) {
124+ try {
125+ return module_::import (
126+ (std::string (" numpy._core." ) + submodule_name).c_str ()
127+ );
128+ } catch (error_already_set &ex) {
129+ if (!ex.matches (PyExc_ImportError)) throw ;
130+ try {
131+ return module_::import (
132+ (std::string (" numpy.core." ) + submodule_name).c_str ()
133+ );
134+ } catch (error_already_set &ex) {
135+ if (!ex.matches (PyExc_ImportError)) throw ;
136+ throw import_error (
137+ std::string (" pybind11 couldn't import " ) + submodule_name + " from numpy."
138+ );
139+ }
140+ }
141+ }
142+
123143template <typename T>
124144struct same_size {
125145 template <typename U>
@@ -263,12 +283,7 @@ struct npy_api {
263283 };
264284
265285 static npy_api lookup () {
266- module_ m;
267- try {
268- m = module_::import (" numpy._core.multiarray" );
269- } catch (error_already_set &) {
270- m = module_::import (" numpy.core.multiarray" );
271- }
286+ module_ m = import_numpy_core_submodule (" multiarray" );
272287 auto c = m.attr (" _ARRAY_API" );
273288 void **api_ptr = (void **) PyCapsule_GetPointer (c.ptr (), nullptr );
274289 npy_api api;
@@ -631,13 +646,11 @@ class dtype : public object {
631646
632647private:
633648 static object _dtype_from_pep3118 () {
634- module_ m;
635- try {
636- m = module_::import (" numpy._core._internal" );
637- } catch (error_already_set &) {
638- m = module_::import (" numpy.core._internal" );
639- }
640- static PyObject *obj = m.attr (" _dtype_from_pep3118" ).cast <object>().release ().ptr ();
649+ module_ m = import_numpy_core_submodule (" _internal" );
650+ static PyObject *obj = m.attr (" _dtype_from_pep3118" )
651+ .cast <object>()
652+ .release ()
653+ .ptr ();
641654 return reinterpret_borrow<object>(obj);
642655 }
643656
0 commit comments