Cython is
$ cat worker.py
class HardWorker(object): u"Almost Sisyphus" def __init__(self, task): self.task = task def work_hard(self): for i in range(100): self.task()
$ cython worker.py
... the fastest way to port Python 2 code to Py3 ;-)
Cython generates very efficient C code
»cdef« keyword declares
Example:
def stupid_lower_case(char* s): cdef Py_ssize_t size, i size = len(s) for i in range(size): if s[i] >= 'A' and s[i] <= 'Z': s[i] += 'a' - 'A' return s
Ask Cython!
$ cat stupidlowercase.py
def stupid_lower_case(char* s): cdef Py_ssize_t size, i size = len(s) for i in range(size): if s[i] >= 'A' and s[i] <= 'Z': s[i] += 'a' - 'A' return s
$ cython --annotate stupidlowercase.py
Example:
cdef extern from "Python.h": # copied from the Python C-API docs: object PyUnicode_DecodeASCII( char* s, Py_ssize_t size, char* errors) cdef extern from "string.h": int strlen(char *s) cdef slightly_better_lower_case(char* s): cdef Py_ssize_t i, size = strlen(s) for i in range(size): if s[i] >= 'A' and s[i] <= 'Z': s[i] += 'a' - 'A' return PyUnicode_DecodeASCII(s, size, NULL)
Dynamic classes and functions with closures
def myfunction(a,b): def closure_function(c): return a+b+c return closure_function
Native support for new buffer protocol
def inplace_negative_grayscale_image( ndarray[unsigned char, 2] image): cdef int i, j for i in range(image.shape[0]): for j in range(image.shape[1]): arr[i, j] = 255 - arr[i, j]
Cython
C-Extensions in Python
... use it, and join the project!