I have a Python module written in C with a number of functions exposed. One of them has a Python definition of:
def SetPowerSupply(voltage, current, supply):
where voltage = float, current = float, and supply = int. On the C side, I have this:
float voltage, current;
int supply;
if (!PyArg_ParseTuple(args, "ffi", &voltage, ¤t, &supply))
{
// Failed to parse
// ...
}
One of my scripters has a script wherein this function fails to parse the arguments, complaining that an integer is expected. So far as I can tell, an integer is in fact being passed in since if in the error branch I do this:
PyObject *num = PyNumber_Float(PyTuple_GetItem(args, 0));
voltage = PyFloat_AsDouble(num);
Py_XDECREF(num);
num = PyNumber_Float(PyTuple_GetItem(args, 1));
current = PyFloat_AsDouble(num);
Py_XDECREF(num);
num = PyNumber_Int(PyTuple_GetItem(args, 2));
supply = PyLong_AsLong(num);
Py_XDECREF(num);
… then everything works as expected. Other script running through this module do not exhibit this behaviour, and I can see no differences. Both of them call the function the same:
SetPowerSupply(37.5, 0.5, 1)
SetPowerSupply(0, 0, 1)
In the offending script I can do something like this:
Any ideas???
Thank you.
Edit:
The problem was caused by another function which was being called several calls prior to this function. It was:
if(!PyArg_ParseTuple(args, "s|siss", &board, &component, &pin, &colorStr, &msg))
{
// Parsing the pin as an int failed, try as a string
if(!PyArg_ParseTuple(args, "s|ssss", &board, &component, &sPin, &colorStr, &msg))
{
// ...
The purpose of this was to basically overload the third argument to accept either a string or numerical value. When someone fed a string to it, the Python error from the failed parse was never cleared. Updated code resolving the issue follows.
if(!PyArg_ParseTuple(args, "s|siss", &board, &component, &pin, &colorStr, &msg))
{
PyErr_Clear();
// Parsing the pin as an int failed, try as a string
if(!PyArg_ParseTuple(args, "s|ssss", &board, &component, &sPin, &colorStr, &msg))
{
// ...
Many thanks to Ignacio for the clue.
One of your other functions is failing to return
Nonewhen appropriate, and you’re catching this error message by accident.