Search code examples
pythonnumpycython

How to use @cython decorator to declare np.ndarray type


I'm having trouble finding any documentation anywhere that specifically addresses this:

The following code:

cdef int foo( double data ):
    # ...
    return int( data )

can be written as:

@cython.returns(cython.int)
@cython.locals(data=cython.double)
def foo(data):
     return int(data)

But I am unable to find an equivalent declaration for:

cdef foo(np.ndarray[double] data):

Using @cython.locals leads to a compilation error.

What's the proper way of decorator declaring a numpy array in cython?


Solution

  • This doesn't appear to be documented anywhere but memoryviews are accepted as a string:

    @cython.returns(cython.int)
    @cython.locals(data="double[:]")
    def foo(data):
         return int(data[0])
    

    I imagine this works generally, however the challenge with numpy arrays is that you have to cimport numpy which I don't think is possible in pure Python code.