is there a reliable way to check at runtime if some python code is "cythonized" or if it us running into a standard Python interpreter ? Thanks !
Answering this because this question comes up as a top response on search engines and the answers aren't helpful.
From http://docs.cython.org/en/latest/src/tutorial/pure.html
import cython
if cython.compiled:
print("Yep, I'm compiled.")
else:
print("Just a lowly interpreted script.")
When I import similar modules and look at their .__file__
attributes I get
In [205]: which.__file__
Out[205]: .../which.py'
In [206]: which_cy.__file__
Out[206]: '.../which_cy.cpython-34m.so'
The cythonized
module is imported from a .so
file, while the python source is .py
(or .pyc
). But there are other ways of compiling code which will also create .so
files. So this doesn't distinguish among compilation routes.
And for individual functions:
In [225]: repr(which.nonzero)
Out[225]: '<function nonzero at 0xb4dd2d1c>'
In [226]: repr(which_cy.nonzero_cy)
Out[226]: '<built-in function nonzero_cy>'
cython
does not 'run' code. It translates a file (e.g. *.pyx) into C code. That is then compiled, producing a loadable module (the .so
) file. That is then imported and run by the Python interpreter. I don't know if there's a way of running the .so
code as a stand along executable.
Or, are you really wondering whether the code in a given compiled module is using tight C code as opposed to calls to Python functions (mainly Python objects and their methods)? You can look at the C code for that. Both are using compiled code, but one has a lot of overhead from checking types, bounds, etc. The whole point to Cython tutorials is ways to shift away the Python generality to faster C definitions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With