python – 缓冲区类型只允许作为函数局部变量,但这就是我正在做的事情

Cython不喜欢闭包中的numpy数组吗?

%%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)

使用稳定版本0.24,我得到:

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

如果我摆脱g的定义,它编译/工作正常.

最佳答案 有几个工作轮:

>仅将类型分配给内部函数中的变量:

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

    return g(1)

这与每次调用g时检查类型相关的成本很小,其重要性取决于你在g中做了多少其他工作.
>使用记忆视图和无类型变量的混合.

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并查看相同的数据,因此您可以通过两种不同的方式访问它.内存视图可以快速进行数组索引.像数组上的标量操作实际上并没有受到类型信息的影响,因此没有理由强迫它成为特定类型.

总之,这是一个限制,但有工作场所(虽然它们不是很整洁).

点赞