[Cython] Safer default exception handling with return type annotations?
stefan_ml at behnel.de
Mon Sep 4 15:32:43 EDT 2017
since PEP 484 type annotations are scheduled for the next release now, I
wonder if we should take the opportunity to change the defaults for the
exception handling of typed cdef functions.
Currently, if you define a function like this:
cdef int func():
It will not actually raise the error but print and ignore it. In order to
make it safe, you have to say
cdef int func() except -1:
It has always been like this, but with PEP 484 type annotations, it becomes
much nicer to keep Cython code Python compatible and actually running in
Python, so that the following is safe when interpreted but not when compiled:
def func(x: cython.int) -> cython.int:
if x < 0:
return x * 2
Since this is new syntax, and no code exists yet that uses it, it would be
safe to change the default here, and to automatically declare this function
as "except? -MIN_INT", for example. The same applies to functions returning
pointers ("except? NULL") or even structs, which could be declared "except *".
This would lead to inconsistencies within Cython, but I think the use case
of Python compatible behaviour is important enough to consider this, and
for code using this syntax, it also feels less likely that the caller is
actual C code that couldn't handle that exception.
More information about the cython-devel