Pyrex
The Pyrex language (http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/) is often the most convenient way to write extensions for Python. Pyrex is a large subset of Python, with the addition of optional C-like types for variables: you can automatically compile Pyrex programs (source files with extension .pyx) into machine code (via an intermediate stage of generated C code), producing Python-importable extensions. See the above URL for all the details of Pyrex programming; in this section, I cover only a few essentials to let you get started with Pyrex.
The limitations of the Pyrex language, compared with Python, are the following:
No nesting of
defandclassstatements in other statements (except that one level ofdefwithin one level ofclassis okay, and indeed is the proper and normal way to define a class’s methods).No
import *, generators, list comprehensions, decorators, or augmented assignment.No
globalsandlocalsbuilt-ins.To give a class a
staticmethodorclassmethod, you must firstdefthe function outside the class statement (in Python, it’s normallydefed within the class).
As you can see, while not quite as rich as Python proper, Pyrex is a vast subset indeed. More importantly, Pyrex adds to Python a few statements that allow C-like declarations, enabling easy generation of machine code (via an intermediate C-code generation step). Here is a simple example; code it in source file hello.pyx in a new empty directory:
def hello(char *name): return "Hello, " + name ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access