【发布时间】:2015-08-05 01:43:47
【问题描述】:
我在combine multiple decorators in python to a single decorator 上发现了这个有趣的问题。
我想在 Cython 中做同样的事情。通常,我的 Cython 代码如下所示:
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
cdef ar[dtype_t, ndim=2] sma_vec(ar[dtype_t, ndim=2] x, int m):
cdef int n
cdef Py_ssize_t i, j
...
或喜欢
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
cpdef ar[dtype_t, ndim=2] sma_vec(ar[dtype_t, ndim=2] x, int m):
cdef int n
cdef Py_ssize_t i, j
...
我倾向于在几乎所有地方重复这三个装饰器@cython.boundscheck(False)、@cython.wraparound(False)、@cython.cdivision(True)。
该页面中给出的常规 Python 的解决方案是
def composed(*decs):
def deco(f):
for dec in reversed(decs):
f = dec(f)
return f
return deco
对于 Cython,我尝试执行以下操作:
cdef composed_for_cdef(*decs):
cdef deco(f):
for dec in reversed(decs):
f = dec(f)
return f
return deco
和
cpdef composed_for_cpdef(*decs):
cpdef deco(f):
for dec in reversed(decs):
f = dec(f)
return f
return deco
但我在编译过程中遇到错误:
cdef composed_for_cdef(*decs):
cdef deco(f):
^
------------------------------------------------------------
stat\movavg.pyx:12:16: C function definition not allowed here
我什至尝试了常规 Python 的解决方案(如上所示),但出现错误:
@composed(cython.boundscheck(False), cython.wraparound(False), cython.cdivision(True))
^
------------------------------------------------------------
stat\movavg.pyx:24:0: Cdef functions/classes cannot take arbitrary decorators.
【问题讨论】:
-
考虑到 Cython 的装饰器如何与编译器交互,我认为您尝试做的事情是不可能的。这就像试图将所有
__future__导入放在一个模块中并import *以打开未来的语句。 -
cython 装饰器实际上是返回一个新的函数对象,还是增加参数然后返回它?
-
@Eric,我不确定我理解你的问题。