Compiling Your Python Code with Cython

hrenski

hrenski

Posted on November 15, 2019

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 utilities.py file with a toy function.

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

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

On my computer, these steps produce an ".so" (shared object) file utilities.cpython-37m-x86_64-linux-gnu.so 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!

code

💖 💪 🙅 🚩
hrenski
hrenski

Posted on November 15, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related