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
中进行的其他工作量。混合使用内存 View 和非类型化变量。
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
查看相同的数据,因此您可以通过两种不同的方式访问它。内存 View 的数组索引很快。数组上的标量运算实际上不受类型信息的影响,因此实际上没有理由强制它成为特定类型。
总而言之,这是一个限制,但也有变通办法(虽然它们不是很整洁)。
关于python - 缓冲区类型只允许作为函数局部变量,但这就是我正在做的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41914252/