2

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

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

double[::1] which corresponds to the python float type
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.