[Cython] automatically raise MemoryError on exceptional C return values

Robert Bradshaw robertwb at gmail.com
Thu Aug 9 01:45:33 CEST 2012


On Tue, Aug 7, 2012 at 2:53 AM, Stefan Behnel <stefan_ml at behnel.de> wrote:
> Hi,
>
> given how ubiquitous manual memory management is in C, I think it would be
> nice to let Cython generate the exception raising also for C, not only for
> C++. The difference is this:
>
>   cdef extern from "...":
>       char* make_new_buffer() except NULL as MemoryError
>       int append_to_buffer(char* buffer, char* value) \
>                                      except -1 as MemoryError
>
>   c_buffer = make_new_buffer()           # raises MemoryError on NULL
>   append_to_buffer(c_buffer, "testdata") # raises MemoryError on -1
>   append_to_buffer(c_buffer, "moredata") # raises MemoryError on -1
>
> versus this:
>
>    cdef extern from "...":
>        char* make_new_buffer()
>        int append_to_buffer(char* buffer, char* value)
>
>    c_buffer = make_new_buffer()
>    if c_buffer is NULL:
>        raise MemoryError()
>    if append_to_buffer(c_buffer, "testdata") == -1:
>        raise MemoryError()
>    if append_to_buffer(c_buffer, "moredata") == -1:
>        raise MemoryError()
>
> I don't think it's necessary to support this for anything but MemoryError,
> since you'd normally want a formatted error message for everything else.
>
> Alternative colours for the bike shed:
>
>     char* make_new_buffer() except NULL raise MemoryError
>
>     char* make_new_buffer() raise MemoryError for NULL
>
>     char* make_new_buffer() raise MemoryError from NULL
>
> What do you think?

I'm +0.5 (with a preference to the "except NULL as MemoryError"
flavor). Basically, it is new syntax to make up for the lack of proper
meta programming. Alternatively (just throwing it out there, not sure
if it's a good idea), could this be done as a decorator of some sort?
That's how one would write such a concept in Python. The need to fix
types does constrain things.

- Robert


More information about the cython-devel mailing list