Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you compile a .py file with cython instead of a pyx file?

Tags:

python

cython

I have a file foo.py, and it contains a very slow function that takes 8 minutes to compute. However, when I change the file to foo.pyx and compile it with cython with no other changes, it takes 5 minutes to compute.

My question is: if I run cython foo.py instead of cython foo.pyx and then run gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python2.7 -o foo.so foo.c

When I run import foo, will python import the .py file or the compiled .so file? Does the pyx really need to be there, and is there a way to force it to take the .so over the .py if it exists?

The reason for this is that I cannot change the name of foo.py without breaking code on other people's machines, but I'd really like it to be faster for my tests cases. It would be great if I could just compile it locally without worrying about breaking code elsewhere.

(I'm testing this as we speak, but its taking awhile)

like image 899
Erotemic Avatar asked Oct 01 '22 18:10

Erotemic


1 Answers

I just tried it on Windows with some Cython code I have been working with recently. The compiled module takes precedence. This was also confirmed in both of the following questions:

What is the precedence of python compiled files in imports?

Python shared object module naming convention

like image 189
IanH Avatar answered Oct 05 '22 11:10

IanH