Pierre de Buyl's homepage

Developing a Cython library

For some time, I have used Cython to accelerate parts of Python programs. One stumbling block in going from Python/NumPy code to Cython code is the fact that one cannot access NumPy's random number generator from Cython without explicit declaration. Here, I give the steps to make a pip-installable 'cimportable' module.

The aim

The aim is that, starting with a Python code reading

import numpy as np

for i in range(N):
    x = x + np.random.normal()

to Cython code

cimport numpy as np

cdef int i, N
cdef double x
N = 100
x = 0
for i in range(N):
    x = x + np.random.normal()

With obvious benefit of using the same module for the random number generator with a simple interface.

The challenge

Building a c-importable module just depends on having a corresponding .pxd file available in the path. The idea behing .pxd file is that they contain C-level (or cdef level) declarations whereas the implementation go in the .pyx file with the same basename.

Comments !

Generated with Pelican. Theme based on MIT-licensed Skeleton.