fossekall
fossekall

Reputation: 521

Typed memoryview not allow inside if

I have a pyx function which will get a numpy array. I don't know the dimensions before run time. It is easy to check, but the problem is I have a numpy array x with with dimesion 1 or 2. I want to check in order to set the correct typed memoryview:

if len(x.shape>1):
   cdef double [:,::1] cview_x = x
else:
   cdef double [::1] cview_x = x

But I get an error message which says that cdef is not allowed here. Do not understand why?

Upvotes: 1

Views: 256

Answers (2)

Bi Rico
Bi Rico

Reputation: 25813

You're trying to dynamically do type declarations, but type declarations are needed by Cython and the compiler at compile time. When you compile your cython code, cython uses the static type information you've provided to optimize the code. If the types are not static, ie you don't know the type or dimension before runtime, cython cannot include that information at compile time.

There are two main ways to solve this issue, one is to define different functions for each possible type, ie something like this:

def myFun1D(double[::1] array):
    pass

def myFun2D(double[:, ::1] array):
    pass

def foo(array):
    cdef double r
    if array.ndim == 1:
        r = myFun1D(array)
    elif array.ndim == 2:
        r = myFun2D(array)

The second option is to simply not type declare array, and allow cython to treat it as a dynamically typed python object.

Upvotes: 3

ryyker
ryyker

Reputation: 23218

...cdef is not allowed here. Do not understand why?

The short answer is that you are likely running into a scope issue related to the fact that Python and C have different scoping rules.

...when you make an assignment to a variable in a scope, that variable is automatically considered by Python to be local to that scope and shadows any similarly named variable in any outer scope.

From here (read #4)

Also, small disscussion here on scope differences, etc.

Upvotes: 0

Related Questions