Buffer types are only allowed as local function variables, but what I do

Cython doesn't like numpy arrays in closure?

%%cython
import numpy as np
cimport numpy as np

def f(np.ndarray[double, ndim=1] a):
    def g (double b):
        return a+b

    return g(1)

Using the stable version 0.24, I get:

Error compiling Cython file:
------------------------------------------------------------
...
import numpy as np
cimport numpy as np

def f(np.ndarray[double, ndim=1] a):
     ^
------------------------------------------------------------

cython_magic.pyx:4:6: Buffer types only allowed as function local variables

If I get rid of the definition g, it compiles / works fine.

+4
source share
1 answer

There are several rounds:

  • Assign a type to a variable only inside an internal function:

    def f(a):
        def g (double b):
            cdef np.ndarray[double, ndim=1] a_typed = a
            return a_typed+b
    
        return g(1)
    

    This is a small cost associated with checking the type of each call g, the value of which depends on what other work you are doing in g.

  • Use a mixture of memory and untyped variables.

    def f(a):
       cdef double[:] memview_of_a = a
    
       def g(double b):
           memview_of_a[0] = 0 # example of indexing operation
           return a+b
    
       return g(1)
    

    , memview_of_a a , . . , , , .

, , ( ).

+1

Source: https://habr.com/ru/post/1668134/


All Articles