12
/* reduce() *************************************************************/
15
functools_reduce(PyObject *self, PyObject *args)
17
PyObject *seq, *func, *result = NULL, *it;
19
if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
24
it = PyObject_GetIter(seq);
26
PyErr_SetString(PyExc_TypeError,
27
"reduce() arg 2 must support iteration");
32
if ((args = PyTuple_New(2)) == NULL)
38
if (args->ob_refcnt > 1) {
40
if ((args = PyTuple_New(2)) == NULL)
44
op2 = PyIter_Next(it);
54
PyTuple_SetItem(args, 0, result);
55
PyTuple_SetItem(args, 1, op2);
56
if ((result = PyEval_CallObject(func, args)) == NULL)
64
PyErr_SetString(PyExc_TypeError,
65
"reduce() of empty sequence with no initial value");
77
PyDoc_STRVAR(reduce_doc,
78
"reduce(function, sequence[, initial]) -> value\n\
80
Apply a function of two arguments cumulatively to the items of a sequence,\n\
81
from left to right, so as to reduce the sequence to a single value.\n\
82
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
83
((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
84
of the sequence in the calculation, and serves as a default when the\n\
12
90
/* partial object **********************************************************/
247
325
"Tools that operate on functions.");
249
327
static PyMethodDef module_methods[] = {
328
{"reduce", functools_reduce, METH_VARARGS, reduce_doc},
250
329
{NULL, NULL} /* sentinel */