Type checking inside a C extension... mystery solved

Jon Perez jbperez808 at yahoo.com
Tue Apr 6 15:00:12 EDT 2004


Stephen Horne wrote:

> Python exceptions aren't converted to C exceptions, and the Python C
> API doesn't use C exceptions at all. There is a good reason for this.
> C doesn't have exceptions - C++ does, but this is a C API.

Ah... now I get this seemingly mysterious behaviour.

If PyString_AsString() attempts to convert a non-string Python object to a
C string, the exception is not thrown from within it, it only sets a flag
indicating that such an exception should eventually be thrown.

While the C extension function itself does need to return a NULL for said
exception occur, it does need to to return to Python runtime first to
trigger the exception.


> Python C API functions often return zero for error IIRC, so...
> 
>   if (PyString_AsString(strobj) == 0)  {  return 0;  }
> 
> Should ensure that the Python exception raised by PyString_AsString is
> propogated correctly.

This also answers my earlier question.  So there is no need to do a
PyString_Check() before feeding a value to PyString_AsString(), just
check the return value of PyString_AsString()...

Thanks everyone.



More information about the Python-list mailing list