1

Im trying to initiate a fixed sized array within a cython class so multiple methods can use it. How can that be done?

cdef class My Class:
    cdef public np.ndarray[np.float, ndim=1] myarr
    def __cinit__(self,int history_length):
        self.myarr = np.empty(history_length, dtype=np.float)

I am getting an error saying:

buffer types only allowed as function local variables

Is there a way to declare this and access this?

Thanks

user1234440
  • 22,521
  • 18
  • 61
  • 103

1 Answers1

3

I believe the buffer syntax type[::1] is preferred in cython i.e.

import numpy as np
cimport numpy as np
cdef class MyClass:
    cdef float[::1] myarr
    def __cinit__(self,int history_length):

        self.myarr = np.empty(history_length, dtype=np.float)

Edit: the above code assumes that you define an array continuous in memory, which by default for numpy arrays is the c style (i.e. row continuous). Defining it float[:] would state that you are expecting a float buffer not necessarily continuous.

cvanelteren
  • 1,633
  • 9
  • 16
  • double[::1] which corresponds to the python float type – ev-br May 01 '21 at 15:08
  • Not sure if that holds in cython, dtype can also be registered with double for example. But you are right that python doesn't have float and double distinction. – cvanelteren May 01 '21 at 17:14