Skip to content
Ashwin Vangipuram edited this page Sep 24, 2020 · 3 revisions

Cython

Cython is a powerful language/framework which acts as a static compiler from Python to C. It provides static typing and lets you easily call C functions within Python, which is our main use case. Note that the Python C API also actually provides tools to turn C functions into Python modules, but this method is very verbose/clunky while Cython is relatively intuitive and simple.

Overview

We will only give a very brief overview. There are a lot of specifics that are needed to really understand Cython, which can be learned from the documentation pages https://cython.readthedocs.io/en/latest/. The documentation isn't really in any order unfortunately, but most of these pages are very useful for us.

Cython's usefulness comes primarily from Cython functions and Cython classes, which are both defined using cdef instead of def. Additionally, every type within a Cython function must be typed, with either Python or Cython types. So you should declare variables with int num or str line. The final core feature we use is that you can extern C functions from header files, which you see in the .pxd files. These C functions can directly be called in our Cython code which is the magical part of Cython.

To use this Cython file, we first need to compile this Cython code into a Python module. This is done in the setup.py file and with a command in the Makefile. Then, the Cython module can be imported just like any other Python module and its public functions can be used. This is a really broad overview, so please read the Cython documentation above.

Usage

We use Cython in our repo just for the Student API. The main need for it is that the student code is in Python and needs to important a Python API. However, this API needs to call C functions because Runtime is written in C. This is where we use Cython to bridge the gap.