Pyrex lets you translate selected Python functions and libraries to C and compile them to native machine code. Pyrex is Python... with a couple of additional keywords like "cdef" and "int" to statically type variables.
Basically, the Pyrex development cycle is:
- write and debug the application in Python
- add data type keywords and convert to .c files
- compile, install and use
Instructions for Pyrex
- Install Pyrex in 'site-packages' in 'Lib' in your Python directory.
- Write and test your Python application as you normally would.
- Profile your code to select opportunities for performance improvements.
- Isolate the target functions and restructure into modules saving as .pyx files.
- In the selected modules, add keywords to data type the variables. Some of the keywords include: "cdef", "char", "short", "int", "long", "float", "double", "void", "unsigned", "object".
cdef class Spam:
cdef int amount
def primes(int kmax):
cdef int n, k, i
cdef int p
result = 
if kmax > 1000:
kmax = 1000
k = 0
n = 2
while k < kmax:
i = 0
while i < k and n % p[i] <> 0:
i = i + 1
if i == k:
p[k] = n
k = k + 1
n = n + 1
- Save as a .pyx file.
python Pyrex.py <xxxxx>.pyxto create .c file.
- Compile and link the .c file to create a library. Use gcc to get a .so; use VC++ to get a .dll.
- Install the libraries and enjoy.
More information is available at:
Pyrex home page: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/
Michael's Quick Guide to Pyrex: http://www.cosc.canterbury.ac.nz/%7Empj17/pyrex-guide/
Another alternative is Psyco. Psyco is somewhat 'nicer' because you have less to do to get it running and there is the potential for it to be faster than typical native code (as are some Java JIT optimizations). ...but you pay a penalty for the run-time compilation. With Pyrex you do a one-time compile, link and install for each target platform.
With Pyrex you must also identify the data type of each variable which is often not too difficult. Psyco doesn't care, but Psyco can get confused if a variable's data type changes mid-execution.
Both Pyrex and Psyco seem easier to use than SWIG.
Both Pyrex and Psyco are in development so all language features may not yet be supported.