Not to be mistaken by CPython!
It is a superset of python that allows the developer to write python-like code but with elements of C++, such as static typing. Since it is a compiled language, it is much more efficient than python This is mainly used in scientific computing software and other programs that rely on performance, since raw Python can be fairly slow.
# pythagoras.pyx
cimport math # Uses cimport for math.h functions
def pythagoras_theorem(int a, int b):
cdef double c = math.sqrt(a**2 + b**2) # cdef for cython variable declaration
return c
It needs to a secondary setup.py file to run like so:
from setuptools import setup
from Cython.Build import cythonize
setup(
ext_modules=cythonize("pythagoras.pyx")
)
Then on a terminal run the following. It will compile the code ( a .so
file on Unix systems or a .pyd
on Windows)
$python3 setup.py build_ext --inplace
Finally to use it on a python file, all that it is needed to do is to import it as you would import a library.
import pythagoras
print(pythagoras.pythagoras_theorem(3, 4)) # Deve imprimir 5.0