Search code examples
c++numpynumpy-ndarraypython-extensions

How to modernize code that uses deprecated NumPy C API?


The following C or C++ code, intended for use in a Python extension module, defines a function f that returns a NumPy array.

#include <Python.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>

PyObject* f()
{
    auto* dims = new npy_intp[2];
    dims[0] = 3;
    dims[1] = 4;

    PyObject* pyarray = PyArray_SimpleNew(2, dims, NPY_DOUBLE);

    double* array_buffer = (double*)PyArray_DATA((PyArrayObject*)pyarray);
    for (size_t i = 0; i < dims[0]; ++i)
        for (size_t j = 0; j < dims[1]; ++j)
            array_buffer[j*dims[0]+i] = j+100+i;

    delete[] dims;

    return pyarray;
}

If the #define statement is removed, then the compiler (or preprocessor) raises a warning #warning "Using deprecated NumPy API, disable it with ...". How to modernize the above code? Or how to find the response in the NumPy documentation djungle?


Solution

  • The code is up to date. There is no need for modernization. The code line

    #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
    

    is required by bad design. See the discussion on the NumPy issue tracker, https://github.com/numpy/numpy/issues/21865.