[capi-sig] Getting Numbers in C

Hrvoje Niksic hniksic at xemacs.org
Sat Jul 21 01:07:57 CEST 2007

Campbell Barton <cbarton at metavr.com> writes:

> 		pyfloat = PyNumber_Float(value);

It might be a good idea to return -1 immediately if this returns
NULL.  That way you prevent clobbering the real exception with an
"invalid argument" exception returned by PyFloat_AsDouble.

If PyNumber_Float succeeds, but pyfloat turns out not to be float,
then the invalid argument exception is perfectly fine.

> However Im wondering if this is advisable, with PyErr_Occurred() its
> possible that some other part of the API (even a totaly separate
> API) sets the error string but dosnt return an error value. - Any
> suggestions?

Requiring the caller to check for PyErr_Occurred seems like bad style,
but I'm not sure that it's an actual problem, as long as it's clearly

As far as I know, no part of the API is allowed to set the error
string and not return an error value because that breaks other parts
of Python.  Consider this function:

static PyObject *
  PyErr_SetString(PyExc_TypeError, "test");
  return Py_None;

Calling it subtly breaks Python:

>>> import foo
>>> foo.test()
>>> import sys
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: test

The exception lingered until the first function that relies on
PyErr_Occurred() to test for an exception, in this case PyImport_*.

More information about the capi-sig mailing list