C API: Making a context manager

Stefan Behnel stefan_ml at behnel.de
Tue Nov 1 13:03:12 EDT 2011


Chris Kaynor, 01.11.2011 17:19:
> On Tue, Nov 1, 2011 at 8:57 AM, Stefan Behnel wrote:
>> Chris Kaynor, 31.10.2011 19:34:
>>> I am currently rewritting a class using the Python C API to improve
>>> performance of it, however I have not been able to find any
>>> documentation about how to make a context manager using the C API.
>>
>> You should take a look at Cython. It makes these things *so* much easier.
>
> Unfortunately, all of the code has to be fully compatible with CPython
> 2.6 - it needs to function inside of Maya, which has CPython 2.6
> embedded, and to which we do not have the source code.

This sounds like you're misunderstanding what Cython is. Cython compiles 
(and optimises) your Python code into fast C code that uses the C-API (and 
that can happily call into external C code etc.). So you get basically the 
same (and sometimes better) speed, but without all the C-level hassle and 
maintenance issues. The C code that Cython generates is fully compatible 
with CPython 2.4 up to the latest 3.3, and that includes 2.6.


> While not all parts of our code base are used inside of Maya, most of
> the performance-critical items are to some degree or another.
>
> In this particular case, the connected context manager is not heavily
> used (outside of unittests) and itself is not performance critical,
> but the much of the rest of the package (and thus the class) it is
> part of is.

In that case, I advise you to leave the context manager code as is, and 
just compile the module that you are trying to speed up (and which, IIUC is 
currently written in Python) with Cython, then optimise the parts of it 
that need more speed by injecting static typing. Here's a quick howto:

http://docs.cython.org/src/quickstart/cythonize.html

Stefan




More information about the Python-list mailing list