Skip to content

Commit 83f202a

Browse files
authored
bpo-43706: Use PEP 590 vectorcall to speed up enumerate() (GH-25154)
1 parent 37fad7d commit 83f202a

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Speed up calls to ``enumerate()`` by using the :pep:`590` ``vectorcall``
2+
calling convention. Patch by Dong-hee Na.

Objects/enumobject.c

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,45 @@ enum_new_impl(PyTypeObject *type, PyObject *iterable, PyObject *start)
8181
return (PyObject *)en;
8282
}
8383

84+
// TODO: Use AC when bpo-43447 is supported
85+
static PyObject *
86+
enumerate_vectorcall(PyObject *type, PyObject *const *args,
87+
size_t nargsf, PyObject *kwnames)
88+
{
89+
assert(PyType_Check(type));
90+
PyTypeObject *tp = (PyTypeObject *)type;
91+
Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
92+
Py_ssize_t nkwargs = 0;
93+
if (nargs == 0) {
94+
PyErr_SetString(PyExc_TypeError,
95+
"enumerate() missing required argument 'iterable'");
96+
return NULL;
97+
}
98+
if (kwnames != NULL) {
99+
nkwargs = PyTuple_GET_SIZE(kwnames);
100+
}
101+
102+
if (nargs + nkwargs == 2) {
103+
if (nkwargs == 1) {
104+
PyObject *kw = PyTuple_GET_ITEM(kwnames, 0);
105+
if (!_PyUnicode_EqualToASCIIString(kw, "start")) {
106+
PyErr_Format(PyExc_TypeError,
107+
"'%S' is an invalid keyword argument for enumerate()", kw);
108+
return NULL;
109+
}
110+
}
111+
return enum_new_impl(tp, args[0], args[1]);
112+
}
113+
114+
if (nargs == 1 && nkwargs == 0) {
115+
return enum_new_impl(tp, args[0], NULL);
116+
}
117+
118+
PyErr_Format(PyExc_TypeError,
119+
"enumerate() takes at most 2 arguments (%d given)", nargs + nkwargs);
120+
return NULL;
121+
}
122+
84123
static void
85124
enum_dealloc(enumobject *en)
86125
{
@@ -261,6 +300,7 @@ PyTypeObject PyEnum_Type = {
261300
PyType_GenericAlloc, /* tp_alloc */
262301
enum_new, /* tp_new */
263302
PyObject_GC_Del, /* tp_free */
303+
.tp_vectorcall = (vectorcallfunc)enumerate_vectorcall
264304
};
265305

266306
/* Reversed Object ***************************************************************/

0 commit comments

Comments
 (0)