Why jupyter notebook only prints the cython result once?

二次信任 提交于 2020-08-19 10:54:34

问题


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
%%cython
def cfunc(int n):
    cdef int a = 0
    for i in range(n):
        a += i
    return a

print(cfunc(10))

However, it only prints out the result 45 once. When I run the print function, the cell doesn't show 45 anyone.

Is there any problems with the code? How can I make the cell prints out 45 just the same as a normal python code? Thanks.


回答1:


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:

  1. A file called _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).
  2. This file is cythonized and build to a c-extension called _cython_magic_b599dcf313706e8c6031a4a7058da2a2.
  3. This extension gets imported - this is the moment your code prints 45, and everything from this module is added to the global namespace.

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.



来源:https://stackoverflow.com/questions/60802385/why-jupyter-notebook-only-prints-the-cython-result-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!