Reputation: 3334
I am trying to use Cython in Jupyterlab:
%load_ext Cython
%%cython -a
def add (int x, int y):
cdef int result
result = x + y
return result
add(3,67)
error:
File "<ipython-input-1-e496e2665826>", line 9
def add (int x, int y):
^
SyntaxError: invalid syntax
What am I missing?
Upvotes: 2
Views: 285
Reputation: 12189
Update:
I just measured cpdef
vs def
and the difference between score was quite a low one (45(cpdef
) vs 52(def
), smaller = better/faster), so for your function it might not matter if called just a few times, but having that chew through a large amount of data might do some real difference.
If that's not applicable for you, just call that %load_ext
in a separate cell, keep def
and that should be enough.
(Cython 0.29.24, GCC 9.3.0, x86_64)
Use cpdef
to make it C-like function, but also to expose it to Python, so you can call it from Jupyter (because Jupyter is using Python, unless specified by the %%cython
magic func). Also, check the Early Binding for Speed section.
cpdef add (int x, int y):
cdef int result
result = x + y
return result
Also make sure to check Using the Jupyter notebook which explains that the %
needs to be in a separate cell as ead mentioned in the comments.
Upvotes: 3
Reputation: 532093
add
has to be defined with cdef
, not def
.
cdef add (int x, int y):
cdef int result
result = x + y
return result
add(3,67)
Upvotes: -1