Skip to content

Commit 04ff762

Browse files
committed
avoid looping over the dict twice
1 parent 3d19683 commit 04ff762

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

Modules/_operator.c

+7-4
Original file line numberDiff line numberDiff line change
@@ -1576,7 +1576,7 @@ methodcaller_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15761576
{
15771577
methodcallerobject *mc;
15781578
PyObject *name, *key, *value;
1579-
Py_ssize_t nargs, i, ppos;
1579+
Py_ssize_t nargs;
15801580

15811581
if (PyTuple_GET_SIZE(args) < 1) {
15821582
PyErr_SetString(PyExc_TypeError, "methodcaller needs at least "
@@ -1622,13 +1622,16 @@ methodcaller_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
16221622
memcpy(mc->vectorcall_args + 1, PySequence_Fast_ITEMS(mc->args),
16231623
nargs * sizeof(PyObject *));
16241624
if (kwds) {
1625-
mc->vectorcall_kwnames = PySequence_Tuple(kwds);
1625+
const Py_ssize_t nkwds = PyDict_Size(kwds);
1626+
1627+
mc->vectorcall_kwnames = PyTuple_New(nkwds);
16261628
if (!mc->vectorcall_kwnames) {
16271629
return NULL;
16281630
}
1629-
i = ppos = 0;
1631+
Py_ssize_t i = 0, ppos = 0;
16301632
while (PyDict_Next(kwds, &ppos, &key, &value)) {
1631-
mc->vectorcall_args[1 + nargs + i] = value;
1633+
PyTuple_SET_ITEM(mc->vectorcall_kwnames, i, Py_NewRef(key));
1634+
mc->vectorcall_args[1 + nargs + i] = value; // borrowed reference
16321635
++i;
16331636
}
16341637
}

0 commit comments

Comments
 (0)