NumPy C-API: Convert Object Type to Number Type

Function

PyObject* PyArray_TypeObjectFromType(int); 

converts the type number for the scalar type NumPy (NPY_BOOL, NPY_BYTE, ...) into the corresponding type object.

How do you do the inverse conversion, from a type object for a scalar NumPy type to an appropriate type number?

Edit: The following code is based on Quatford's answer. It accepts both types of objects, such as int and numpy.int16, and strings, such as "int", "int", and "int16".

 int numpyScalarTypeNumber(PyObject* obj) { PyArray_Descr* dtype; if(!PyArray_DescrConverter(obj, &dtype)) return NPY_NOTYPE; int typeNum = dtype->type_num; Py_DECREF(dtype); return typeNum; } 
+6
source share
1 answer

If you can get PyArray_Descr structs and not PyArray_TypeObject s, you can just look at the type_num field. The descr structures can be obtained through the type number using PyArray_DescrFromType . If you look at this link, there are several more functions for converting various things into descr structures. They are probably more useful in general than type objects, and contain references to their types.

+4
source

Source: https://habr.com/ru/post/903600/


All Articles