A Cython pyx file needs to be translated to C code (cythonized) and compiled before it can be used from Python. A common approach is to create an extension module which is then imported in a Python program.
For this example we create three files:
hello.pyx
contains the Cython code.test.py
is a Python script that uses the hello extension.setup.py
is used to compile the Cython code.from libc.math cimport pow
cdef double square_and_add (double x):
"""Compute x^2 + x as double.
This is a cdef function that can be called from within
a Cython program, but not from Python.
"""
return pow(x, 2.0) + x
cpdef print_result (double x):
"""This is a cpdef function that can be called from Python."""
print("({} ^ 2) + {} = {}".format(x, x, square_and_add(x)))
# Import the extension module hello.
import hello
# Call the print_result method
hello.print_result(23.0)
from distutils.core import Extension, setup
from Cython.Build import cythonize
# define an extension that will be cythonized and compiled
ext = Extension(name="hello", sources=["hello.pyx"])
setup(ext_modules=cythonize(ext))
This can be done by, using cython hello.pyx
to translate the code to C and then compile it using gcc
. An easier way is to let distutils handle this:
$ ls
hello.pyx setup.py test.py
$ python setup.py build_ext --inplace
$ ls
build hello.c hello.cpython-34m.so hello.pyx setup.py test.py
The shared object (.so) file can be imported and used from Python, so now we can run the test.py
:
$ python test.py
(23.0 ^ 2) + 23.0 = 552.0