run Cython in Jupyter cdef

点点圈 提交于 2019-12-10 15:37:21

问题


I am looking for incorporate some cython to speed my code. I get a issue with running cython code in Jupyter.

cell 1:

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

cell 2:

fuc()

error:

---------------------------------------------------------------------------
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)

Looks like cdef is using differently in Jupyter, how could I use cdef in Jupyter notebook?


回答1:


cdef functions can only be called from Cython, not Python. The documentation says

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.

(having already stated that "C functions" are defined by cdef and "Python functions" by def.)

Use a def function in Cython instead. It's still compiled by Cython. You can still cdef types within your def function.




回答2:


how could I use cdef in Jupyter notebook?

Try to change cdef into cpdef.



来源:https://stackoverflow.com/questions/43725273/run-cython-in-jupyter-cdef

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!