I want to have a Cython "cdef" object with a NumPy member, and be able to use fast buffer access. Ideally, I would do something like:
import numpy as np cimport numpy as np cdef class Model: cdef np.ndarray[np.int_t, ndim=1] A def sum(self): cdef int i, s=0, N=len(self.A) for 0 <= i < N: s += self.A[i] return s def __init__(self): self.A = np.arange(1000)
Unfortunately, Cython can't compile this, with the error Buffer types only allowed as function local variables
.
The workaround I'm using is to declare the buffer attributes on a new local variable, assigned to the object member:
cdef class Model: cdef np.ndarray A def sum(self): cdef int i, s=0, N=len(self.A) cdef np.ndarray[np.int_t, ndim=1] A = self.A for 0 <= i < N: s += A[i] return s
This becomes really annoying if you want to have multiple methods accessing the same data structures -- which seems like a pretty common use case, no?
Is there a better solution that doesn't require re-declaring the types inside every method?
There is the option to work with memory slices or cython arrays http://docs.cython.org/src/userguide/memoryviews.html
import numpy as np cimport numpy as np cdef class Model: cdef int [:] A def sum(self): for 0 <= i < N: s += self.A[i] return s def __init__(self): self.A = np.arange(1000)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With