DEV Community


Posted on

Compiling Your Python Code with Cython

Python is a great language to test and prototype with... partly because it is interpreted, so the code is readily referenced and changed. But there may be times when you'd like to compartmentalize your Python code (for example by compiling it); this is easily done using Cython. I'll outline the steps below (make sure you have Cython installed!). If you'd like to find out more, check out the Cython documentation page.

  1. Take all of your your Python code that you'd like to compile and add it to a utilities file. Here, as an example, we'll make a file with a toy function.

    import numpy as np
    def everyother(a):
        return np.ascontiguousarray(a[::2])
  2. Next, create a file:

    from distutils.core import setup
    from Cython.Build import cythonize
    setup(ext_modules = cythonize(""))
  3. Finally, compile it by typing python build_ext --inplace.

On my computer, these steps produce an ".so" (shared object) file that you can import in a Python script or interactive instance.

In [1]: import numpy as np                                                                                                                                                                                                                                                     

In [2]: import utilities as ut                                                                                                                                                                                                                                                 

In [3]: a = np.arange(12)                                                                                                                                                                                                                                                      

In [4]: a                                                                                                                                                                                                                                                                      
Out[4]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

In [5]: ut.everyother(a)                                                                                                                                                                                                                                                       
Out[5]: array([ 0,  2,  4,  6,  8, 10])

That's all there is to it!


Top comments (0)