在Jupyter cdef中运行Cython

时间:2017-05-01 19:32:40

标签: python python-3.x cython jupyter-notebook

我正在寻找合并一些cython来加速我的代码。 我遇到了在Jupyter中运行cython代码的问题。

单元格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

但如果我这样做,它就可以正常工作。

%%cython
def fuc():
    cdef int a = 0
    for i in range(10):
        a += i
        print(a)

看起来cdef在Jupyter中的使用方式不同,我怎么能在Jupyter笔记本中使用cdef?

2 个答案:

答案 0 :(得分:6)

cdef functions can only be called from Cython, not Python。文档说

  

在Cython模块中,Python函数和C函数可以自由地相互调用,但只能通过解释的Python代码从模块外部调用Python函数。

(已经说过&#34; C函数&#34;由cdef和&#34; Python函数&#34;由def定义。)

在Cython中使用def函数。它仍然由Cython编译。您仍然可以在cdef功能中def种类型。

答案 1 :(得分:1)

  

我怎么能在Jupyter笔记本中使用cdef?

尝试将 cdef 更改为 cpdef