Cython’s two major use cases [are]: extending the CPython interpreter with fast binary modules, and interfacing Python code with external C libraries.
The idea is that
The source code gets translated into optimized C/C++ code and compiled as Python extension modules
The "Hello world" example works fine. I install Cython with
easy_install
. Following the tutorial, in hello.pyx
I have:I write another file
setup.hello.py
:And I do this:
From the interpreter we can import functions from
hello.so
:Now, to do something a bit more interesting. Suppose I want to use the
sqrt
function from the C library declared in math.h
. I write a file cy_script.pyx
:The print statement is there for testing, as you'll see. We write another file
setup.py
with this:We build it as before:
In the interpreter:
Notice that following the first statement we get execution of
print f(2)
; that is, cy_script
was actually imported, but the names defined in cy_script
are not available to us.I have to look into more to see how to do this. What's the difference between the first example and the second one?
[UPDATE: Answer from Stack Overflow, as always!
Substitute
cpdef double f(int i):
, and it'll work. ] [UPDATE2: There's an even cooler way to do this:
Details here. ]