I am new to cython(only use it for doing a little hw now). I use the following code to see a general idea of it in jupyter notebook.
%load_ext Cython
%%cyth
When running %%cython
-magic a lot happens under the hood. One can see parts of it when calling the magic in verbose mode, i.e. %%cython --verbose
:
_cython_magic_b599dcf313706e8c6031a4a7058da2a2.pyx
is generated. b599dcf313706e8c6031a4a7058da2a2
is the sha1-hash of the %%cython
-cell, which is needed for example to be able to reload a %%cython
-cell (see this SO-post)._cython_magic_b599dcf313706e8c6031a4a7058da2a2
.When you execute the cell again, nothing of the above happens: given the sha-hash the machinery can see, that this cell was already executed and loaded - so nothing to be done. Only when the content of the cell is changed and thus its hash the cash will not be used but the 3 steps above executed.
To enforce that the steps above are performed one has to pass --force
(or -f
) options to the %%cython
-magic-cell, i.e.:
%%cython --force
...
# 45 is printed
However, because building extension anew is quite time consuming one would probably prefer the following
%%cython
def cfunc(int n):
cdef int a = 0
for i in range(n):
a += i
return a
# put the code of __main__ into a function
def cython_main():
print(cfunc(10))
# execute the old main
cython_main()
and now calling cython_main()
in a new cell, so it gets reevaluated the same way the normal python code would.