Run Cython in Jupyter cdef

I am looking to include some cython to speed up my code. I am getting problem 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()

      

Mistake:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-48-10789e9d47b8> in <module>()
----> 1 fuc()

NameError: name 'fuc' is not defined

      

but if i do that it works fine.

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

      

It looks like cdef uses Jupyter differently, how can I use cdef in Jupyter notebook?

+4


source to share


3 answers


cdef

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

Inside a Cython module, Python functions and C functions are free to call each other, but only Python functions can be called from Python because of the interpreted Python code.



(having already stated that "C functions" are defined cdef

and "Python functions" are on def

.)

Use a function def

in Cython instead . It is still compiled by Cython. You can still cdef

type in your function def

.

+6


source


how can i use cdef in jupyter notebook?



Try changing cdef to cpdef .

+1


source


Using cpdef for Cython methods to be used in Python cells is better than just using def .

For example, you can potentially gain performance gain by setting the return value of a method to a static type, such as when using cdef, and still access the method from Python cells, as when using def. This way you solve the inter-cell access problem of your method while still getting some Cython features.

0


source







All Articles