I would like to write some Pure Python with Cython decorator, but when I rename my NONE.PY to NONE.PYX I've got an error. To workaround this issue I need to wrap each attribute with a pure python definition call without decorator. I wonder why...
here the module none.pyx (if you rename it to none.py, you will have no issue at all)
import cython
@cython.cfunc
@cython.returns(cython.double)
@cython.locals(n=cython.int,i=cython.int,r=cython.int)
def ccrange(n):
r=0
for i in range(n):
r+=i
return r
def crange(n): return ccrange(n)
and the python test file test_none.py:
import pyximport; pyximport.install()
import none
n=10000
print ">>pure python call>>",none.crange(n)
print ">>cython call>>",none.ccrange(n)
Result with none.pyx:
pure python call>> 49995000.0 cython call>> Traceback (most recent call last): File "C:\\Users\\damien\\python4d\\bacoland\\test_none.py", line 6, in print ">>cython call>>",none.ccrange(n)
AttributeError: 'module' object has no attribute 'ccrange'
Rename none.pyx to none.py, give:
pure python call>> 49995000 cython call>> 49995000
Thanks for Help! Have a NiceDay :-)
EDIT: Avoid the decorator @cython.cfunc is breaking the speed avantage of cython... Consider this following code with and without @cython.cfunc:
@cython.cfunc
@cython.returns(cython.double)
@cython.locals(n=cython.int)
def fibo_c(n):
if n == 0 or n == 1:
return n
return fibo_c(n-2) + fibo_c(n-1)
@cython.cfunc
decorator is an equivalent to cdef
ing a function (see here for details), so this function is accessible only within C
code. So, to make it accessible from Python get rid of @cython.cfunc
.
此时应更换你的@cython.cfunc
(相当于cdef
,即从仅C调用)由@cython.ccall
(相当于cpdef
,即都可以访问使用慢速Python的调用约定和快速的C调用约定)。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.