mirror of
https://github.com/python/cpython.git
synced 2025-07-29 06:05:00 +00:00
follup to #3473: don't duplicate the reduce code
This commit is contained in:
parent
8692c79ba9
commit
08336e30ad
1 changed files with 10 additions and 56 deletions
|
@ -2001,68 +2001,22 @@ is printed without a trailing newline before reading.");
|
||||||
static PyObject *
|
static PyObject *
|
||||||
builtin_reduce(PyObject *self, PyObject *args)
|
builtin_reduce(PyObject *self, PyObject *args)
|
||||||
{
|
{
|
||||||
PyObject *seq, *func, *result = NULL, *it;
|
static PyObject *functools_reduce = NULL;
|
||||||
|
|
||||||
if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
|
if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
|
||||||
"use functools.reduce()", 1) < 0)
|
"use functools.reduce()", 1) < 0)
|
||||||
return NULL;
|
return NULL;
|
||||||
|
|
||||||
if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
|
if (functools_reduce == NULL) {
|
||||||
|
PyObject *functools = PyImport_ImportModule("functools");
|
||||||
|
if (functools == NULL)
|
||||||
return NULL;
|
return NULL;
|
||||||
if (result != NULL)
|
functools_reduce = PyObject_GetAttrString(functools, "reduce");
|
||||||
Py_INCREF(result);
|
Py_DECREF(functools);
|
||||||
|
if (functools_reduce == NULL)
|
||||||
it = PyObject_GetIter(seq);
|
|
||||||
if (it == NULL) {
|
|
||||||
PyErr_SetString(PyExc_TypeError,
|
|
||||||
"reduce() arg 2 must support iteration");
|
|
||||||
Py_XDECREF(result);
|
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
return PyObject_Call(functools_reduce, args, NULL);
|
||||||
if ((args = PyTuple_New(2)) == NULL)
|
|
||||||
goto Fail;
|
|
||||||
|
|
||||||
for (;;) {
|
|
||||||
PyObject *op2;
|
|
||||||
|
|
||||||
if (args->ob_refcnt > 1) {
|
|
||||||
Py_DECREF(args);
|
|
||||||
if ((args = PyTuple_New(2)) == NULL)
|
|
||||||
goto Fail;
|
|
||||||
}
|
|
||||||
|
|
||||||
op2 = PyIter_Next(it);
|
|
||||||
if (op2 == NULL) {
|
|
||||||
if (PyErr_Occurred())
|
|
||||||
goto Fail;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result == NULL)
|
|
||||||
result = op2;
|
|
||||||
else {
|
|
||||||
PyTuple_SetItem(args, 0, result);
|
|
||||||
PyTuple_SetItem(args, 1, op2);
|
|
||||||
if ((result = PyEval_CallObject(func, args)) == NULL)
|
|
||||||
goto Fail;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Py_DECREF(args);
|
|
||||||
|
|
||||||
if (result == NULL)
|
|
||||||
PyErr_SetString(PyExc_TypeError,
|
|
||||||
"reduce() of empty sequence with no initial value");
|
|
||||||
|
|
||||||
Py_DECREF(it);
|
|
||||||
return result;
|
|
||||||
|
|
||||||
Fail:
|
|
||||||
Py_XDECREF(args);
|
|
||||||
Py_XDECREF(result);
|
|
||||||
Py_DECREF(it);
|
|
||||||
return NULL;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
PyDoc_STRVAR(reduce_doc,
|
PyDoc_STRVAR(reduce_doc,
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue