define and run cython function with ipython

I learned this trick in the book Cython: A Guide for Python Programmer.

After having both Cython and IPython installed, we can load the cythonmagic extension with:

In [1]: %load_ext cythonmagic

Now we have 3 extra magic functions in the session:

In [4]: %%cython
   ...: def sum_up(*numbers):
   ...:     cdef int s = 0
   ...:     for n in numbers:
   ...:         s += n
   ...:     return s
   ...:
In [5]: sum_up(1, 2, 3)
Out[5]: 6
In [16]: x = 3.14

In [17]: y = 2

In [18]: %%cython_inline
   ....: return x * y
   ....:
Out[18]: 6.28
In [21]: %%cython_pyximport double
....: def f(x):
....:     return 2.0 * x
....:
In [22]: !ls *.pyx
double.pyx
In [23]: f(4)
Out[23]: 8.0

Comments