Skip to content

Commit 56a4338

Browse files
author
benjamin.peterson
committed
follup to #3473: don't duplicate the reduce code
git-svn-id: http://svn.python.org/projects/python/trunk@65802 6015fed2-1504-0410-9fe1-9d1591cc4771
1 parent 70ab907 commit 56a4338

1 file changed

Lines changed: 10 additions & 56 deletions

File tree

Python/bltinmodule.c

Lines changed: 10 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -2001,68 +2001,22 @@ is printed without a trailing newline before reading.");
20012001
static PyObject *
20022002
builtin_reduce(PyObject *self, PyObject *args)
20032003
{
2004-
PyObject *seq, *func, *result = NULL, *it;
2004+
static PyObject *functools_reduce = NULL;
20052005

20062006
if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
20072007
"use functools.reduce()", 1) < 0)
20082008
return NULL;
20092009

2010-
if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
2011-
return NULL;
2012-
if (result != NULL)
2013-
Py_INCREF(result);
2014-
2015-
it = PyObject_GetIter(seq);
2016-
if (it == NULL) {
2017-
PyErr_SetString(PyExc_TypeError,
2018-
"reduce() arg 2 must support iteration");
2019-
Py_XDECREF(result);
2020-
return NULL;
2021-
}
2022-
2023-
if ((args = PyTuple_New(2)) == NULL)
2024-
goto Fail;
2025-
2026-
for (;;) {
2027-
PyObject *op2;
2028-
2029-
if (args->ob_refcnt > 1) {
2030-
Py_DECREF(args);
2031-
if ((args = PyTuple_New(2)) == NULL)
2032-
goto Fail;
2033-
}
2034-
2035-
op2 = PyIter_Next(it);
2036-
if (op2 == NULL) {
2037-
if (PyErr_Occurred())
2038-
goto Fail;
2039-
break;
2040-
}
2041-
2042-
if (result == NULL)
2043-
result = op2;
2044-
else {
2045-
PyTuple_SetItem(args, 0, result);
2046-
PyTuple_SetItem(args, 1, op2);
2047-
if ((result = PyEval_CallObject(func, args)) == NULL)
2048-
goto Fail;
2049-
}
2010+
if (functools_reduce == NULL) {
2011+
PyObject *functools = PyImport_ImportModule("functools");
2012+
if (functools == NULL)
2013+
return NULL;
2014+
functools_reduce = PyObject_GetAttrString(functools, "reduce");
2015+
Py_DECREF(functools);
2016+
if (functools_reduce == NULL)
2017+
return NULL;
20502018
}
2051-
2052-
Py_DECREF(args);
2053-
2054-
if (result == NULL)
2055-
PyErr_SetString(PyExc_TypeError,
2056-
"reduce() of empty sequence with no initial value");
2057-
2058-
Py_DECREF(it);
2059-
return result;
2060-
2061-
Fail:
2062-
Py_XDECREF(args);
2063-
Py_XDECREF(result);
2064-
Py_DECREF(it);
2065-
return NULL;
2019+
return PyObject_Call(functools_reduce, args, NULL);
20662020
}
20672021

20682022
PyDoc_STRVAR(reduce_doc,

0 commit comments

Comments
 (0)