I am using Cython in jupyter notebook.
As I know, Cython compiles def functions.
But when I want to call function with global variable it doesn't see it.
Are there any method to call function with variable?
one1 = 1
%%cython
cimport numpy as np
cdef nump(number1):
return number1 + 1
nump(one1)
****This is sample code, to show moderators
In an
Ipython
session I can do:That is I define a
cython
function, but call it from Python with the global variable.If I define the function with
cdef
I need to invoke it with adef
function.fooc
is not visible from Python.If I attempt to use
one
from within thecython
file (magic cell) I get an error, the equivalent of a Python NameErrorThe
ipython
session variableone
is not visible from within the magic cell.Working from @DavidW's answer, this
import
works:This
fooc
is not accessible from Python.Note that the
import
uses the value ofone
at compile time.Your code has a few errors, but I think the one you are asking about is one the line
nump(one1)
which gives the errorThis is because your
%%cython
snippets are essentially built in their own module. The%%cython
magic in jupyter is more designed to create compiled functions that are accessible in your main code, rather than to access variables in your main code.One solution is to add the line
at the start of your Cython block, to gain access to the "top level" scope. The answer @hpaulj has posted suggests the better approach where you define functions in Cython and use them outside the block.