When I compile a cell with cython, it seems Jupyter forgets the compiled function in the next cell. This seems to me to be not right. What is going wrong?
I am using version 5.0.0 of the notebook, and
Python 3.6.1 |Anaconda custom (x86_64)| (default, May 11 2017, 13:04:09)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]
Here is a MWE that produces the problem:
Cell 1:
%load_ext Cython
Cell 2:
%%cython
cdef int foo():
return 3
print(foo())
This produces:
3
In the next cell, I have
print(foo())
This produces:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-3-9701608cebc0> in <module>()
----> 1 print(foo())
NameError: name 'foo' is not defined
I guess it's because you didn't defined your foo
function as available in python (with cpdef
) but only only give it a C signature (with cdef
) so it can only be called from cython code.
In the cell 2 you can call it because you are still using cython code but in your cell 3 you are back in pure python and the function isn't available. There is various way to get the result from the foo
function in python :
%%cython
# Not reachable in pure python:
cdef int foo():
return 3
# Python visible function signature:
cpdef int foo2():
return 3
# Or a wrapper around the cython function:
def foo3():
return foo()
You can now try to call foo2()
or foo3()
in your python code.
See one of the relevant part of the documentation if you haven't see it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With