Why jupyter notebook only prints the cython result once?

后端 未结 1 566
[愿得一人]
[愿得一人] 2021-01-16 03:25

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         


        
1条回答
  •  伪装坚强ぢ
    2021-01-16 03:30

    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.

    0 讨论(0)
提交回复
热议问题