Exception Handling (C - extending python)

Stefan Behnel stefan_ml at behnel.de
Tue Oct 25 04:22:04 EDT 2011


Ulrich Eckhardt, 25.10.2011 08:49:
> Am 23.10.2011 14:41, schrieb Stefan Behnel:
>> That's just fine. If you are interested in the inner mechanics of the
>> CPython runtime, reading the source is a very good way to start getting
>> involved with the project.
>>
>> However, many extension module authors don't care about these inner
>> mechanics and just use Cython instead. That keeps them from having to
>> learn the C-API of CPython, and from tying their code too deeply into
>> the CPython runtime itself.
>
> Could you elaborate a bit? What are the pros and cons of writing an
> extension module using the Cython API compared to using the CPyothon API?

No cons. ;)

Cython is not an API, it's a programming language. It's Python, but with 
extended support for talking to C/C++ code (and also Fortran). That means 
that you don't have to use the C-API yourself, because Cython will do it 
for you.


> In particular, how portable is it? Can I compile a module in one and use it
> in the other?

They both use the CPython C-API internally. It's just that you are not 
using it explicitly in your code, so you (can) keep your own code free of 
CPython-isms.

It's substantially more portable than the "usual" hand-written code, 
because it generates C code for you that compiles and works in CPython 2.4 
up to the latest 3.3 in-development version, and also with all major C/C++ 
compilers, etc. It also generates faster glue code than you would write, 
e.g. for data type conversion and argument unpacking in function calls. So 
it speeds up thin wrappers automatically for you.

That doesn't mean that you can't get the same level of speed and 
portability in hand-written code. It just means that you don't have to do 
it yourself. Saves a lot of time, both during development and later during 
the maintenance cycle. Basically, it allows you to focus on the 
functionality you want to implement, rather than the implementation details 
of CPython, and also keeps the maintenance overhead at that level for you.


> Don't I just tie myself to a different API, but tie myself
> nonetheless?

There's a port to plain Python+ctypes underways, for example, which you 
could eventually use in PyPy. Try to do that at the C-API level.

Stefan




More information about the Python-list mailing list