[Cython] Exception instantiation

Stefan Behnel stefan_ml at behnel.de
Wed Mar 21 09:03:43 CET 2012


Hi,

I was made aware of a difference between the ways Cython and CPython raise
exceptions. In CPython, the exception is always instantiated immediately,
even if you raise a plain type, i.e.

    raise TypeError

will actually raise a TypeError() instance. In Cython, the exception is
only stored, not instantiated. The difference can show when the
instantiation fails for some reason or has other side effects. Depending on
*when* and *if* the exception is actually instantiated, these effects may
show at unexpected times during execution, or may be not occur at all in
some corner cases (e.g. when the exception is shadowed by another one in
Py2 or caught by an except block in Cython that contains only C code).

I think this should change. We may consider leaving it as it is for known
exception types that are created without arguments, but otherwise, and
especially for user provided exceptions, we should take the safer route of
always instantiating them, like CPython does. That implies a certain
performance hit in some rather rare cases (of which an explicitly raised
StopIteration is the most visible one, if not exempted), but under normal
conditions where an exception is regularly caught at some point, the
overhead is the same and it would have less surprising corner cases.

Stefan


More information about the cython-devel mailing list