Pyrex is Python with C data types

Pyrex lets you write code that mixes Python and C data types and compiles it into a C extension for Python.

There are differences in the C and Python type systems, C checks types when code is compiled, while Python check types during run-time. Pyrex contains a mixture of C and Python. Pyrex is specially designed for writing Python extension modules. It acts as a bridge between the world of Python and world of C.

SWIG is the best known tool which takes a definition file consisting of a mixture of C code and specialised declarations, and produces an extension module. In many cases you can use it without knowing about the Python/C API. But you need to use API calls if any substantial restructuring of the data is required between Python and C.

Another well known tool is PyInline , it lets you embed pieces of C code in the midst of a Python file, and automatically extracts them and compiles them into an extension.

Pyrex aims to go far beyond of these tools . Pyrex deals with the basic types just as easily as SWIG, but it also lets you write code to convert between arbitrary Python data structures and arbitrary C data structures also Pyrex lets you define new built-in Python types just as easily as you can define new classes in Python.

The reasons for creating C modules for Python:

  • C modules are faster than Python modules.
  • You want to wrap a C library to give Python functionality that it does not already have.

To compile a Pyrex module you will need:

  • Python 2.2
  • Pyrex (version 0.5)
  • C compiler

Limitations :
Pyrex is not quite a full superset of Python. Following are some limitations :

  • Function definitions (whether using def or cdef) cannot be nested within other function definitions.
  • Class definitions can only appear at the top level of a module, not inside a function.
  • The import * form of import is not allowed anywhere,other forms of the import statement are fine,
  • Generators cannot be defined in Pyrex.
  • The globals() and locals() functions cannot be used.
  • Class and function definitions cannot be placed inside control structures.
  • In-place arithmetic operators (+=, etc) are not yet supported.
  • List comprehensions are not yet supported.
  • There is no support for Unicode.
  • Special methods of extension types cannot have functioning docstrings.
  • The string literals can not be used as comments as Pyrex doesn’t optimize and accept them.

We can hope the improvements in the coming new versions. The latest Version is 0.9.3

Reference:
Pyrex – a Language for Writing Python Extension Modules

Content Team

The IndicThreads Content Team posts news about the latest and greatest in software development as well as content from IndicThreads' conferences and events. Track us social media @IndicThreads. Stay tuned!

Leave a Reply