1300: #line 1521 "mxTools.pak"
1301:
1302: Py_C_Function( mxTools_index,
1303: "index(condition,sequence)\n\n"
1304: "Return the index of the first item for which condition\n"
1305: "returns true. A ValueError is raised in case no item\n"
1306: "is found.")
1307: {
1308: PyObject *condition;
1309: PyObject *list = 0;
1310: PyObject *argtuple = 0;
1311: register int i;
1312: int n;
1313: int length;
1314:
1315: Py_Get2Args("OO",condition,list);
1316:
1317: length = PySequence_Length(list);
1318: if (length < 0)
1319: goto onError;
1320:
1321: argtuple = PyTuple_New(1);
1322: if (!argtuple)
1323: goto onError;
1324:
1325: for(i = 0, n = -1; i < length; i++) {
1326: register PyObject *v;
1327: register PyObject *w;
1328:
1329: v = PySequence_GetItem(list,i);
1330: if (!v)
1331: goto onError;
1332:
1333: /* Replace the argtuple entry with the new item */
1334: Py_XDECREF(PyTuple_GET_ITEM(argtuple,0));
1335: PyTuple_SET_ITEM(argtuple,0,v);
1336:
1337: /* Let's see what condition thinks about this item */
1338: w = PyEval_CallObject(condition,argtuple);
1339: if (!w)
1340: goto onError;
1341: if (PyObject_IsTrue(w)) {
1342: n = i;
1343: Py_DECREF(w);
1344: break;
1345: }
1346: Py_DECREF(w);
1347: }
1348: if (n == -1)
1349: Py_Error(PyExc_ValueError,
1350: "condition is false for all items in sequence");
1351:
1352: Py_DECREF(argtuple);
1353: return PyInt_FromLong((long)n);
1354:
1355: onError:
1356: Py_XDECREF(argtuple);
1357: return NULL;
1358: }
1359: