From 96edc5e42a22dbfc6c579730e23b9c95fe16774d Mon Sep 17 00:00:00 2001 From: Cody Maloney Date: Thu, 29 Oct 2026 18:02:55 -0700 Subject: [PATCH 1/3] gh-87613: Support **kwargs in Argument Clinic vectorcall `@vectorcall` with `**kwargs` always delegated to the keyword helper, which only reads a kwargs dict, so it couldn't be generated. The vectorcall now parses positionals with the shared positional emitter and builds the dict from kwnames only when there are keywords, otherwise passing NULL, as the tuple parser does. The `*args` and `**kwargs` parsers take the calling convention explicitly rather than reading `self.fastcall`, which describes the Python-visible entry point having stack style args, not the vectorcall. Co-Authored-By: Claude Opus 5.5 --- Tools/clinic/libclinic/converters.py | 16 ++++-- Tools/clinic/libclinic/parse_args.py | 79 ++++++++++++---------------- 2 files changed, 46 insertions(+), 49 deletions(-) diff --git a/Tools/clinic/libclinic/converters.py b/Tools/clinic/libclinic/converters.py index e3571eb597f24a..014486f7f469de 100644 --- a/Tools/clinic/libclinic/converters.py +++ b/Tools/clinic/libclinic/converters.py @@ -1437,7 +1437,7 @@ class VarKeywordCConverter(CConverter): def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None: raise AssertionError('should never be called') - def parse_var_keyword(self) -> str: + def parse_var_keyword(self, *, stackargs: bool) -> str: raise NotImplementedError @@ -1448,6 +1448,16 @@ class var_keyword_dict_converter(VarKeywordCConverter): def cleanup(self) -> str: return f'Py_XDECREF({self.parser_name});\n' - def parse_var_keyword(self) -> str: + def parse_var_keyword(self, *, stackargs: bool) -> str: # NULL when there are no keywords: no call allocates an empty dict. - return f"{self.parser_name} = Py_XNewRef(kwargs);\n" + param_name = self.parser_name + if stackargs: + return f""" + if (kwnames != NULL) {{{{ + {param_name} = _PyStack_AsDict(args + nargs, kwnames); + if ({param_name} == NULL) {{{{ + goto exit; + }}}} + }}}} + """ + return f"{param_name} = Py_XNewRef(kwargs);\n" diff --git a/Tools/clinic/libclinic/parse_args.py b/Tools/clinic/libclinic/parse_args.py index 0d62e230b4a56f..4608947cb7fff7 100644 --- a/Tools/clinic/libclinic/parse_args.py +++ b/Tools/clinic/libclinic/parse_args.py @@ -933,11 +933,11 @@ def _parse_vararg(self, *, fastcall: bool) -> str: fastcall=fastcall, limited_capi=self.limited_capi) - def _parse_kwarg(self) -> str: + def _parse_kwarg(self, *, stackargs: bool) -> str: assert self.var_keyword is not None c = self.var_keyword.converter assert isinstance(c, libclinic.converters.VarKeywordCConverter) - return c.parse_var_keyword() + return c.parse_var_keyword(stackargs=stackargs) def _check_positional(self, nargs: str, *, indent: int = 4) -> list[str]: @@ -967,9 +967,8 @@ def _parse_positional_args( ) -> list[str] | None: """Emit per-parameter positional argument parsing. - Shared by parse_pos_only() and the vectorcall paths. Returns the - code snippets, or None if a converter doesn't support parse_arg - (the caller must fall back to a tuple/stack parser). + Returns the code snippets, or None if a converter doesn't support + parse_arg (the caller must fall back to a tuple/stack parser). """ parser_code: list[str] = [] for i, p in enumerate(self.parameters): @@ -998,9 +997,9 @@ def _parse_positional_args( if self.varpos: parser_code.append(libclinic.normalize_snippet( self._parse_vararg(fastcall=fastcall), indent=4)) - elif self.var_keyword: - parser_code.append(libclinic.normalize_snippet(self._parse_kwarg(), - indent=4)) + if self.var_keyword: + parser_code.append(libclinic.normalize_snippet( + self._parse_kwarg(stackargs=fastcall), indent=4)) return parser_code def select_positional_convention(self) -> tuple[str, str]: @@ -1112,48 +1111,38 @@ def parse_pos_only(self) -> None: """, indent=4)) self.parser_body(*parser_code) - def parse_var_keyword(self) -> None: + def parse_var_keyword(self, *, vectorcall: bool = False) -> None: self.flags = "METH_VARARGS|METH_KEYWORDS" - self.parser_prototype = PARSER_PROTOTYPE_KEYWORD - nargs = 'PyTuple_GET_SIZE(args)' + # The vectorcall gets an array of arguments and kwnames, not a tuple + # and a dict: use the converters' fastcall convention, which handles + # that. + if vectorcall: + nargs, argname_fmt = 'nargs', 'args[%d]' + check, arg = '_PyArg_NoPositionalStack', 'nargs' + parser_code = self._vectorcall_type_check() + else: + self.parser_prototype = PARSER_PROTOTYPE_KEYWORD + nargs, argname_fmt = 'PyTuple_GET_SIZE(args)', 'PyTuple_GET_ITEM(args, %d)' + check, arg = '_PyArg_NoPositional', 'args' + parser_code = [] - parser_code = [] if self.varpos is None and self.min_pos == self.max_pos == 0: - self.codegen.add_include('pycore_modsupport.h', - '_PyArg_NoPositional()') - parser_code.append(libclinic.normalize_snippet(""" - if (!_PyArg_NoPositional("{name}", args)) {{ + self.codegen.add_include('pycore_modsupport.h', f'{check}()') + parser_code.append(libclinic.normalize_snippet(f""" + if (!{check}("{{name}}", {arg})) {{{{ goto exit; - }} + }}}} """, indent=4)) else: parser_code.extend(self._check_positional(nargs)) - has_optional = False - for i, p in enumerate(self.parameters): - parse_arg = p.converter.parse_arg( - f'PyTuple_GET_ITEM(args, {i})', - p.get_displayname(i+1), - limited_capi=self.limited_capi, - ) - assert parse_arg is not None - if has_optional or p.is_optional(): - has_optional = True - parser_code.append(libclinic.normalize_snippet(""" - if (%s < %d) {{ - goto skip_optional; - }} - """, indent=4) % (nargs, i + 1)) - parser_code.append(libclinic.normalize_snippet(parse_arg, indent=4)) - if has_optional: - parser_code.append("skip_optional:") - - if self.varpos: - parser_code.append(libclinic.normalize_snippet( - self._parse_vararg(fastcall=self.fastcall), indent=4)) - if self.var_keyword: - parser_code.append(libclinic.normalize_snippet(self._parse_kwarg(), indent=4)) - self.parser_body(*parser_code) + pos_code = self._parse_positional_args( + argname_fmt=argname_fmt, nargs=nargs, + limited_capi=self.limited_capi, fastcall=vectorcall) + assert pos_code is not None + parser_code.extend(pos_code) + body = self.vectorcall_body if vectorcall else self.parser_body + body(*parser_code) def use_converters(self) -> None: """Prepare for parsing all arguments by a single call. @@ -1456,7 +1445,7 @@ def handle_new_or_init(self) -> None: if self.func.kind is METHOD_INIT: self.return_value_declaration = "int {parser_retval} = -1;" - if self.func.vectorcall and 'METH_KEYWORDS' in self.flags: + if self.parser_prototype == PARSER_PROTOTYPE_KEYWORD_HELPER: self._new_or_init_delegate_to_helper() else: self._new_or_init_parser_body() @@ -1624,8 +1613,6 @@ def _vectorcall_positional(self, *, arity_checked: Already have a number of arguments check. """ - # The vectorcall gets an array of arguments, not a tuple: use the - # converters' fastcall convention, which handles that. pos_code = self._parse_positional_args( argname_fmt='args[%d]', nargs='nargs', limited_capi=False, fastcall=True) @@ -1781,7 +1768,7 @@ def parse_vectorcall(self) -> None: if not self.parameters and not self.varpos and not self.var_keyword: self.parse_vectorcall_no_args() elif self.var_keyword is not None: - self.parse_vectorcall_kw_required() + self.parse_var_keyword(vectorcall=True) elif self.pos_only == len(self.parameters): self.parse_vectorcall_pos_only() elif any(p.is_keyword_only() for p in self.parameters) or self.varpos: From a0b90936bc74464b29efbf4cbd9d70ed7a4572ad Mon Sep 17 00:00:00 2001 From: Cody Maloney Date: Wed, 28 Oct 2026 02:32:27 -0700 Subject: [PATCH 2/3] gh-87613: Allow 'as' on Argument Clinic **kwargs parameters `*args as name` already set the C name; `**kwargs as name` failed to parse because the 'as' regex only allowed a single leading star. Co-Authored-By: Claude Opus 5.5 --- Lib/test/test_clinic.py | 9 +++++++++ Tools/clinic/libclinic/dsl_parser.py | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_clinic.py b/Lib/test/test_clinic.py index ac0ed2c77d4e4a..cb90e751e57729 100644 --- a/Lib/test/test_clinic.py +++ b/Lib/test/test_clinic.py @@ -1847,6 +1847,15 @@ def test_c_name(self): """) self.assertEqual("os_stat_fn", function.c_basename) + def test_var_keyword_c_name(self): + function = self.parse_function(""" + module foo + foo.bar + **kwargs as kwds: dict + """) + p = function.parameters['kwargs_as_kwds'] + self.assertEqual("kwds", p.converter.name) + def test_base_invalid_syntax(self): block = """ module os diff --git a/Tools/clinic/libclinic/dsl_parser.py b/Tools/clinic/libclinic/dsl_parser.py index 7ac6b3b3d25394..c514844bb8866d 100644 --- a/Tools/clinic/libclinic/dsl_parser.py +++ b/Tools/clinic/libclinic/dsl_parser.py @@ -996,7 +996,7 @@ def parse_parameter(self, line: str) -> None: # handle "as" for parameters too c_name = None - m = re.match(r'(?:\* *)?\w+( +as +(\w+))', line) + m = re.match(r'(?:\*{1,2} *)?\w+( +as +(\w+))', line) if m: c_name = m[2] line = line[:m.start(1)] + line[m.end(1):] From f15f9694ae02d2addf53d6cca7960dda5e8e7470 Mon Sep 17 00:00:00 2001 From: Cody Maloney Date: Sun, 22 Nov 2026 16:11:13 -0800 Subject: [PATCH 3/3] gh-87613: Test @vectorcall with **kwargs in _testclinic Co-Authored-By: Claude Opus 5.5 --- Lib/test/test_clinic.py | 15 +++++++ Modules/_testclinic.c | 33 ++++++++++++++++ Modules/clinic/_testclinic.c.h | 71 +++++++++++++++++++++++++++++++++- 3 files changed, 118 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_clinic.py b/Lib/test/test_clinic.py index cb90e751e57729..cb4ed55fabbbc1 100644 --- a/Lib/test/test_clinic.py +++ b/Lib/test/test_clinic.py @@ -5855,6 +5855,20 @@ def test_vc_kwonly_missing_required(self): with self.assertRaises(TypeError): ac_tester.VcKwOnly() + def test_vc_kwds(self): + with self.assertRaises(TypeError): + ac_tester.VcKwds() + with self.assertRaises(TypeError): + ac_tester.VcKwds(y='y') + with self.assertRaises(TypeError): + ac_tester.VcKwds(1, 2, 3) + self.assertEqual(ac_tester.VcKwds(1), (1, None, None)) + self.assertEqual(ac_tester.VcKwds(1, 2), (1, 2, None)) + self.assertEqual(ac_tester.VcKwds(1, a='a', b='b'), + (1, None, {'a': 'a', 'b': 'b'})) + kwds = {'y': 'y', 'z': 'z'} + self.assertEqual(ac_tester.VcKwds(1, 2, **kwds), (1, 2, kwds)) + def test_parse_errors_match_slot(self): # tp_vectorcall and tp_new/tp_init slot should match in argument parsing # error messages. Explicit calls to __new__ and __init__, as well as @@ -5880,6 +5894,7 @@ def through_init(cls): through_new(ac_tester.VcNew), through_new(ac_tester.VcNewBase), through_new(ac_tester.VcKwOnly), + through_new(ac_tester.VcKwds), through_init(ac_tester.VcInit), ] invalid_calls = [ diff --git a/Modules/_testclinic.c b/Modules/_testclinic.c index 007dd30068c38f..31f59698727bf5 100644 --- a/Modules/_testclinic.c +++ b/Modules/_testclinic.c @@ -26,6 +26,7 @@ custom_converter(PyObject *obj, custom_t *val) static PyTypeObject VcNew_Type; static PyTypeObject VcNewBase_Type; static PyTypeObject VcKwOnly_Type; +static PyTypeObject VcKwds_Type; #include "clinic/_testclinic.c.h" @@ -2671,6 +2672,37 @@ static PyTypeObject VcKwOnly_Type = { }; +/* VcKwds: @vectorcall + **kwargs. __new__ returns the parsed arguments. */ + +/*[clinic input] +class _testclinic.VcKwds "PyObject *" "&VcKwds_Type" +@classmethod +@vectorcall +_testclinic.VcKwds.__new__ as vc_kwds_new + a: object + b: object = None + / + **kwds: dict +[clinic start generated code]*/ + +static PyObject * +vc_kwds_new_impl(PyTypeObject *type, PyObject *a, PyObject *b, + PyObject *kwds) +/*[clinic end generated code: output=481e680d2e76fdbd input=1c27337c5efd9a79]*/ +{ + return pack_arguments_newref(3, a, b, kwds); +} + +static PyTypeObject VcKwds_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "_testclinic.VcKwds", + .tp_basicsize = sizeof(PyObject), + .tp_flags = Py_TPFLAGS_DEFAULT, + .tp_new = vc_kwds_new, + .tp_vectorcall = vc_kwds_vectorcall, +}; + + /*[clinic input] output push @@ -2886,6 +2918,7 @@ _testclinic_exec(PyObject *m) { PyTypeObject *static_types[] = { &TestClass, &VcNew_Type, &VcNewBase_Type, &VcKwOnly_Type, + &VcKwds_Type, }; for (size_t i = 0; i < Py_ARRAY_LENGTH(static_types); i++) { if (PyModule_AddType(m, static_types[i]) < 0) { diff --git a/Modules/clinic/_testclinic.c.h b/Modules/clinic/_testclinic.c.h index dcc60c7341cbc3..4527ae213f021e 100644 --- a/Modules/clinic/_testclinic.c.h +++ b/Modules/clinic/_testclinic.c.h @@ -5309,4 +5309,73 @@ vc_kwonly_vectorcall(PyObject *type, PyObject *const *args, kwnames ? PyTuple_GET_SIZE(kwnames) : 0, NULL, kwnames); } -/*[clinic end generated code: output=b54b37db716469cd input=a9049054013a1b77]*/ + +static PyObject * +vc_kwds_new_impl(PyTypeObject *type, PyObject *a, PyObject *b, + PyObject *kwds); + +static PyObject * +vc_kwds_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) +{ + PyObject *return_value = NULL; + PyObject *a; + PyObject *b = Py_None; + PyObject *__clinic_kwds = NULL; + + if (!_PyArg_CheckPositional("VcKwds", PyTuple_GET_SIZE(args), 1, 2)) { + goto exit; + } + a = PyTuple_GET_ITEM(args, 0); + if (PyTuple_GET_SIZE(args) < 2) { + goto skip_optional; + } + b = PyTuple_GET_ITEM(args, 1); +skip_optional: + __clinic_kwds = Py_XNewRef(kwargs); + return_value = vc_kwds_new_impl(type, a, b, __clinic_kwds); + +exit: + /* Cleanup for kwds */ + Py_XDECREF(__clinic_kwds); + + return return_value; +} + +static PyObject * +vc_kwds_vectorcall(PyObject *type, PyObject *const *args, + size_t nargsf, PyObject *kwnames) +{ + PyObject *return_value = NULL; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *a; + PyObject *b = Py_None; + PyObject *__clinic_kwds = NULL; + + assert(_PyType_CAST(type)->tp_new == vc_kwds_new); + /* Make sure the type object is immutable: the generated + * vectorcall doesn't deal e.g. with users reassigning __init__. */ + assert(PyType_HasFeature(_PyType_CAST(type), Py_TPFLAGS_IMMUTABLETYPE)); + if (!_PyArg_CheckPositional("VcKwds", nargs, 1, 2)) { + goto exit; + } + a = args[0]; + if (nargs < 2) { + goto skip_optional; + } + b = args[1]; +skip_optional: + if (kwnames != NULL) { + __clinic_kwds = _PyStack_AsDict(args + nargs, kwnames); + if (__clinic_kwds == NULL) { + goto exit; + } + } + return_value = vc_kwds_new_impl(_PyType_CAST(type), a, b, __clinic_kwds); + +exit: + /* Cleanup for kwds */ + Py_XDECREF(__clinic_kwds); + + return return_value; +} +/*[clinic end generated code: output=2e36c6f796a4ca09 input=a9049054013a1b77]*/