Open irvinren opened 2 weeks ago
the original explanation of the syntax is
Error return values
In Python (more specifically, in the CPython runtime), exceptions that occur inside of a function are signaled to the caller and propagated up the call stack through defined error return values. For functions that return a Python object (and thus, a pointer to such an object), the error return value is simply the NULL pointer, so any function returning a Python object has a well-defined error return value.
While this is always the case for Python functions, functions defined as C functions or cpdef/@ccall functions can return arbitrary C types, which do not have such a well-defined error return value. By default Cython uses a dedicated return value to signal that an exception has been raised from non-external cpdef/@ccall functions. However, how Cython handles exceptions from these functions can be changed if needed.
A cdef function may be declared with an exception return value for it as a contract with the caller. Here is an example:
cdef int spam() except -1: ...
With this declaration, whenever an exception occurs inside spam, it will immediately return with the value -1. From the caller’s side, whenever a call to spam returns -1, the caller will assume that an exception has occurred and can now process or propagate it. Calling spam() is roughly translated to the following C code
If all possible return values are legal and you can’t reserve one entirely for signalling errors, you can use an alternative form of exception value declaration
cdef int spam() except? -1: ...
The ? indicates that the value -1 may signal an error.
In this case, Cython generates a call to PyErr_Occurred() if the exception value is returned, to make sure it really received an exception and not just a normal result. Calling spam() is roughly translated to the following C code:
ret_val = spam(); if (ret_val == -1 && PyErr_Occurred()) goto error_handler;
There is also a third form of exception value declaration
according to the documentation of Cython @ https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html#error-return-values, the syntax of except? should be recognized as a way to specify the exception value, whereas the syntax is not recognized and the following code is regarded as a syntax error .
Please help fix.
from libc.limits cimport INT_MAX
cpdef int test_func(int input) except ?INT_MAX: return 1
thanks
Xiquan Ren