在Jupyter cdef中运行Cython [英] run Cython in Jupyter cdef
问题描述
我正在寻找合并一些cython来加速我的代码的方法. 我在Jupyter中运行cython代码时遇到问题.
I am looking for incorporate some cython to speed my code. I get a issue with running cython code in Jupyter.
单元格1:
%%cython
cdef fuc():
cdef int a = 0
for i in range(10):
a += i
print(a)
单元格2:
fuc()
错误:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-48-10789e9d47b8> in <module>()
----> 1 fuc()
NameError: name 'fuc' is not defined
但是如果我这样做,它就可以正常工作.
but if i do this, it works fine.
%%cython
def fuc():
cdef int a = 0
for i in range(10):
a += i
print(a)
看起来cdef在Jupyter中使用的方式有所不同,我如何在Jupyter笔记本中使用cdef?
Looks like cdef is using differently in Jupyter, how could I use cdef in Jupyter notebook?
推荐答案
cdef
functions can only be called from Cython, not Python. The documentation says
在Cython模块中,Python函数和C函数可以自由调用,但是只能通过解释后的Python代码从模块外部调用Python函数.
Within a Cython module, Python functions and C functions can call each other freely, but only Python functions can be called from outside the module by interpreted Python code.
(已经声明"C函数"由cdef
定义,"Python函数"由def
定义.)
(having already stated that "C functions" are defined by cdef
and "Python functions" by def
.)
在Cython中使用def
函数.它仍然由Cython编译.您仍然可以在def
函数中使用cdef
类型.
Use a def
function in Cython instead. It's still compiled by Cython. You can still cdef
types within your def
function.
这篇关于在Jupyter cdef中运行Cython的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!