Simon Willison’s Weblog

Subscribe

Pyrex

26th November 2003

Pyrex is a language for writing Python extension modules. It’s pretty interesting—the syntax looks very similar to Python (the authors claim you can write C extension modules without knowing anything about the Python/C API) but uses additional type hints to compile down to ultra efficient C code, ready to be imported in to your Python applications. The prime numbers example maakes things a lot more clear:

#
#  Calculate prime numbers
#

def primes(int kmax):
  cdef int n, k, i
  cdef int p[1000]
  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
      result.append(n)
    n = n + 1
  return result

bash$ python pyrexc primes.pyx
bash$ gcc -shared primes.o -lxosd -o primes.so

>>> import primes
>>> primes.primes(10)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
>>>

I imagine there’s a slight performance impact from using Python’s list data structures instead of a more low level C array, but I doubt it’s significant. In any case, the real promise of Pyrex lies in making it easier to write Python wrappers for existing C libraries—a topic touched on by the Pyrex Documentation.

This is Pyrex by Simon Willison, posted on 26th November 2003.

Next: Why run Windows on an ATM?

Previous: Discovering Berkeley DB

Previously hosted at http://simon.incutio.com/archive/2003/11/26/pyrex