diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-12-03-20-05-38.gh-issue-95757.4WHmNY.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-12-03-20-05-38.gh-issue-95757.4WHmNY.rst new file mode 100644 index 00000000000000..e8d5771039bfcf --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-12-03-20-05-38.gh-issue-95757.4WHmNY.rst @@ -0,0 +1,2 @@ +Speed up calls that unpack arguments with ``*`` or ``**`` into Python +functions that have no named parameters, such as ``def f(*args, **kwargs)``. diff --git a/Python/ceval.c b/Python/ceval.c index 446e6a8be4da91..f319f9d35ef746 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -2126,7 +2126,24 @@ _PyInterpreterFrame * _PyEvalFramePushAndInit_Ex(PyThreadState *tstate, _PyStackRef func, PyObject *locals, Py_ssize_t nargs, PyObject *callargs, PyObject *kwargs, _PyInterpreterFrame *previous) { + PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE( + PyStackRef_AsPyObjectBorrow(func)); bool has_dict = (kwargs != NULL && PyDict_GET_SIZE(kwargs) > 0); + /* callargs already is *args if there are no positional parameters */ + bool pass_args = co->co_argcount == 0 && (co->co_flags & CO_VARARGS); + /* kwargs already is **kwargs if no parameter can be passed by keyword */ + bool pass_kwargs = (has_dict + && (co->co_flags & CO_VARKEYWORDS) + && co->co_argcount == co->co_posonlyargcount + && co->co_kwonlyargcount == 0 + && _PyObject_IsUniquelyReferenced(kwargs) + && _PyDict_HasOnlyStringKeys(kwargs)); + if (pass_args) { + nargs = 0; + } + if (pass_kwargs) { + has_dict = false; + } PyObject *kwnames = NULL; _PyStackRef *newargs; PyObject *const *object_array = NULL; @@ -2179,7 +2196,22 @@ _PyEvalFramePushAndInit_Ex(PyThreadState *tstate, _PyStackRef func, /* No need to decref func here because the reference has been stolen by _PyEvalFramePushAndInit. */ - Py_DECREF(callargs); + if ((pass_args || pass_kwargs) && new_frame != NULL) { + _PyStackRef *local = &new_frame->localsplus[co->co_argcount + + co->co_kwonlyargcount]; + if (pass_args) { + PyStackRef_CLOSE(*local); + *local = PyStackRef_FromPyObjectSteal(callargs); + callargs = NULL; + } + if (pass_kwargs) { + local += (co->co_flags & CO_VARARGS) != 0; + PyStackRef_CLOSE(*local); + *local = PyStackRef_FromPyObjectSteal(kwargs); + kwargs = NULL; + } + } + Py_XDECREF(callargs); Py_XDECREF(kwargs); return new_frame; error: