Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Jupyter Notebook "forget" Cython from one cell to the next?

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
like image 299
Nemis L. Avatar asked Jan 30 '23 18:01

Nemis L.


1 Answers

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.

like image 180
mgc Avatar answered Apr 06 '23 19:04

mgc