Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython says buffer types only allowed as function local variables even for ndarray.copy()

I am new to Cython and encountered this code snippet:

import numpy as np
cimport numpy as np

testarray = np.arange(5)
cdef np.ndarray[np.int_t, ndim=1] testarray1 = testarray.copy()
cdef np.ndarray[np.float_t, ndim=1] testarray2 = testarray.astype(np.float)

During compilation, it said Buffer types only allowed as function local variables. However, I am using .copy() or .astype() which is returning not a memoryview, but a copy. Why is this still happening? How can I get around this?

Thanks!

like image 581
Yuxiang Wang Avatar asked May 23 '14 20:05

Yuxiang Wang


1 Answers

When you define an array in cython using np.ndarray[Type, dim], that is accessing the python buffer interface, and those can't be set as module level variables. This is a separate issue from views vs copies of numpy array data.

Typically if I want to have an array as a module level variable (i.e not local to a method), I define a typed memoryview and then set it within a method using something like (untested):

import numpy as np
cimport numpy as np

cdef np.int_t[:] testarray1

def init_arrays(np.int_t[:] testarray):
    global testarray1
    testarray1 = testarray.copy()
like image 146
JoshAdel Avatar answered Oct 22 '22 14:10

JoshAdel