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

Question:

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?

Asked By: MB.

||

Answers:

I found the following answers in Google Groups:

Try making mySum a cpdef function and decorating the one in the .pxd
file with a cython.locals using the numpy array declaration syntax.

Google Group

You can use a .pxd file and the @cython.locals annotation to declare a
buffer type.

Google Group

Answered By: Joe

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.

Answered By: DavidW
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.