gh-125916: Adapt functools.reduce() to Argument Clinic (#125999)

This commit is contained in:
Sergey B Kirpichev 2024-11-01 23:15:39 +03:00 committed by GitHub
parent 74cf5967f3
commit 51ef54abc4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 72 additions and 24 deletions

View file

@ -932,15 +932,31 @@ _functools_cmp_to_key_impl(PyObject *module, PyObject *mycmp)
/* reduce (used to be a builtin) ********************************************/
// Not converted to argument clinic, because of `args` in-place modification.
// AC will affect performance.
static PyObject *
functools_reduce(PyObject *self, PyObject *args)
{
PyObject *seq, *func, *result = NULL, *it;
/*[clinic input]
_functools.reduce
function as func: object
iterable as seq: object
initial as result: object = NULL
/
Apply a function of two arguments cumulatively to the items of an iterable, from left to right.
This effectively reduces the iterable to a single value. If initial is present,
it is placed before the items of the iterable in the calculation, and serves as
a default when the iterable is empty.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
calculates ((((1 + 2) + 3) + 4) + 5).
[clinic start generated code]*/
static PyObject *
_functools_reduce_impl(PyObject *module, PyObject *func, PyObject *seq,
PyObject *result)
/*[clinic end generated code: output=30d898fe1267c79d input=d233c2670cba7f66]*/
{
PyObject *args, *it;
if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
return NULL;
if (result != NULL)
Py_INCREF(result);
@ -1006,18 +1022,6 @@ functools_reduce(PyObject *self, PyObject *args)
return NULL;
}
PyDoc_STRVAR(functools_reduce_doc,
"reduce(function, iterable[, initial], /) -> value\n\
\n\
Apply a function of two arguments cumulatively to the items of an iterable, from left to right.\n\
\n\
This effectively reduces the iterable to a single value. If initial is present,\n\
it is placed before the items of the iterable in the calculation, and serves as\n\
a default when the iterable is empty.\n\
\n\
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])\n\
calculates ((((1 + 2) + 3) + 4) + 5).");
/* lru_cache object **********************************************************/
/* There are four principal algorithmic differences from the pure python version:
@ -1722,7 +1726,7 @@ PyDoc_STRVAR(_functools_doc,
"Tools that operate on functions.");
static PyMethodDef _functools_methods[] = {
{"reduce", functools_reduce, METH_VARARGS, functools_reduce_doc},
_FUNCTOOLS_REDUCE_METHODDEF
_FUNCTOOLS_CMP_TO_KEY_METHODDEF
{NULL, NULL} /* sentinel */
};