From 68195ffe5f9cd6ca7e6df673da1af545fb648b19 Mon Sep 17 00:00:00 2001 From: Cody Maloney Date: Sat, 21 Nov 2026 20:13:40 -0800 Subject: [PATCH 1/2] gh-162350: Use AC vectorcall for complex() Generate complex.__new__ and its vectorcall with Argument Clinic. To keep accepting a string only as a positional argument (complex('1') but not complex(real='1')), real and imag are declared twice: positional-only and keyword-only, with @text_signature keeping the visible "(real=0, imag=0)". The previous hand-written tp_new wrapper becomes the one-argument conversion called from complex_new_impl(). Error messages change when more than two arguments are passed in total: a duplicated or unknown keyword is now reported as such instead of "takes at most 2 arguments (N given)". Microbenchmarks (pyperf, PGO+LTO): | Benchmark | main | patch | |-------------------------------------|:-------:|:---------------------:| | complex(real=a_float, imag=a_float) | 67.4 ns | 37.9 ns: 1.78x faster | | complex(a_float, imag=a_float) | 62.2 ns | 39.2 ns: 1.59x faster | | complex(a_complex) | 18.9 ns | 12.0 ns: 1.57x faster | | complex(a_float, a_float) | 38.0 ns | 29.2 ns: 1.30x faster | | complex(an_int) | 36.9 ns | 29.9 ns: 1.24x faster | | complex(a_float) | 31.0 ns | 26.0 ns: 1.19x faster | | complex(a_str) | 48.4 ns | 41.8 ns: 1.16x faster | | complex() | 21.1 ns | 18.5 ns: 1.14x faster | Subclass construction (no vectorcall) is unchanged. Co-Authored-By: Claude Opus 5.5 --- Lib/test/test_complex.py | 4 ++ Objects/clinic/complexobject.c.h | 68 +++++++++++++++++++++++++------- Objects/complexobject.c | 61 +++++++++++++++++++--------- 3 files changed, 99 insertions(+), 34 deletions(-) diff --git a/Lib/test/test_complex.py b/Lib/test/test_complex.py index c8d348a4822598..2d220bdeb7cc40 100644 --- a/Lib/test/test_complex.py +++ b/Lib/test/test_complex.py @@ -609,6 +609,10 @@ def check(z, x, y): check(complex(imag=1.5), 0.0, 1.5) check(complex(real=4.25, imag=1.5), 4.25, 1.5) check(complex(4.25, imag=1.5), 4.25, 1.5) + self.assertRaisesRegex(TypeError, r"given by name \('real'\) and position \(1\)", + complex, 4.25, real=1.5) + self.assertRaisesRegex(TypeError, r"given by name \('imag'\) and position \(2\)", + complex, 4.25, 1.5, imag=1.5) # check that the sign of a zero in the real or imaginary part # is preserved when constructing from two floats. diff --git a/Objects/clinic/complexobject.c.h b/Objects/clinic/complexobject.c.h index c7303380de55f4..fd29584c19c1b3 100644 --- a/Objects/clinic/complexobject.c.h +++ b/Objects/clinic/complexobject.c.h @@ -102,10 +102,12 @@ PyDoc_STRVAR(complex_new__doc__, "with the specified real and imaginary components."); static PyObject * -complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i); +complex_new_impl(PyTypeObject *type, PyObject *real_pos, PyObject *imag_pos, + PyObject *r, PyObject *i); static PyObject * -complex_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) +complex_new_helper(PyTypeObject *type, PyObject *const *args, + Py_ssize_t nargs, Py_ssize_t nkw, PyObject *kwargs, PyObject *kwnames) { PyObject *return_value = NULL; #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) @@ -128,42 +130,78 @@ complex_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) # define KWTUPLE NULL #endif // !Py_BUILD_CORE - static const char * const _keywords[] = {"real", "imag", NULL}; + static const char * const _keywords[] = {"", "", "real", "imag", NULL}; static _PyArg_Parser _parser = { .keywords = _keywords, .fname = "complex", .kwtuple = KWTUPLE, }; #undef KWTUPLE - PyObject *argsbuf[2]; + PyObject *argsbuf[4]; PyObject * const *fastargs; - Py_ssize_t nargs = PyTuple_GET_SIZE(args); - Py_ssize_t noptargs = nargs + (kwargs ? PyDict_GET_SIZE(kwargs) : 0) - 0; + Py_ssize_t noptargs = nargs + nkw - 0; + PyObject *real_pos = NULL; + PyObject *imag_pos = NULL; PyObject *r = NULL; PyObject *i = NULL; - fastargs = _PyArg_UnpackKeywords(_PyTuple_CAST(args)->ob_item, nargs, kwargs, NULL, &_parser, + fastargs = _PyArg_UnpackKeywords(args, nargs, kwargs, kwnames, &_parser, /*minpos*/ 0, /*maxpos*/ 2, /*minkw*/ 0, /*varpos*/ 0, argsbuf); if (!fastargs) { goto exit; } + if (nargs < 1) { + goto skip_optional_posonly; + } + noptargs--; + real_pos = fastargs[0]; + if (nargs < 2) { + goto skip_optional_posonly; + } + noptargs--; + imag_pos = fastargs[1]; +skip_optional_posonly: if (!noptargs) { - goto skip_optional_pos; + goto skip_optional_kwonly; } - if (fastargs[0]) { - r = fastargs[0]; + if (fastargs[2]) { + r = fastargs[2]; if (!--noptargs) { - goto skip_optional_pos; + goto skip_optional_kwonly; } } - i = fastargs[1]; -skip_optional_pos: - return_value = complex_new_impl(type, r, i); + i = fastargs[3]; +skip_optional_kwonly: + return_value = complex_new_impl(type, real_pos, imag_pos, r, i); exit: return return_value; } +static PyObject * +complex_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) +{ + return complex_new_helper(type, _PyTuple_CAST(args)->ob_item, + PyTuple_GET_SIZE(args), + kwargs ? PyDict_GET_SIZE(kwargs) : 0, + kwargs, NULL); +} + +static PyObject * +complex_vectorcall(PyObject *type, PyObject *const *args, + size_t nargsf, PyObject *kwnames) +{ + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + + assert(_PyType_CAST(type)->tp_new == complex_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)); + return complex_new_helper(_PyType_CAST(type), args, nargs, + kwnames ? PyTuple_GET_SIZE(kwnames) : 0, + NULL, kwnames); +} + PyDoc_STRVAR(complex_from_number__doc__, "from_number($type, number, /)\n" "--\n" @@ -185,4 +223,4 @@ complex_from_number(PyObject *type, PyObject *number) return return_value; } -/*[clinic end generated code: output=05d2ff43fc409733 input=a9049054013a1b77]*/ +/*[clinic end generated code: output=35512ea9996f9935 input=a9049054013a1b77]*/ diff --git a/Objects/complexobject.c b/Objects/complexobject.c index 4d2b5dc8e4613f..3fc3c4119a52fc 100644 --- a/Objects/complexobject.c +++ b/Objects/complexobject.c @@ -1121,27 +1121,19 @@ complex_subtype_from_string(PyTypeObject *type, PyObject *v) /* The constructor should only accept a string as a positional argument, * not as by the 'real' keyword. But Argument Clinic does not allow * to distinguish between argument passed positionally and by keyword. - * So the constructor must be split into two parts: actual_complex_new() - * handles the case of no arguments and one positional argument, and calls - * complex_new(), implemented with Argument Clinic, to handle the remaining - * cases: 'real' and 'imag' arguments. This separation is well suited - * for different constructor roles: converting a string or number to a complex + * So complex_new() declares 'real' and 'imag' twice: as positional-only and + * as keyword-only parameters. complex_new_impl() calls complex_from_arg() + * for one positional argument and handles the remaining cases itself: + * 'real' and 'imag' arguments. This separation is well suited for + * different constructor roles: converting a string or number to a complex * number and constructing a complex number from real and imaginary parts. */ static PyObject * -actual_complex_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) +complex_from_arg(PyTypeObject *type, PyObject *arg) { PyObject *res = NULL; PyNumberMethods *nbr; - if (PyTuple_GET_SIZE(args) > 1 || (kwargs != NULL && PyDict_GET_SIZE(kwargs))) { - return complex_new(type, args, kwargs); - } - if (!PyTuple_GET_SIZE(args)) { - return complex_subtype_from_doubles(type, 0, 0); - } - - PyObject *arg = PyTuple_GET_ITEM(args, 0); /* Special-case for a single argument when type(arg) is complex. */ if (PyComplex_CheckExact(arg) && type == &PyComplex_Type) { /* Note that we can't know whether it's safe to return @@ -1190,10 +1182,16 @@ actual_complex_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) } /*[clinic input] +@vectorcall @classmethod +@text_signature "(real=0, imag=0)" complex.__new__ as complex_new - real as r: object(c_default="NULL") = 0 - imag as i: object(c_default="NULL") = 0 + real_pos: object = NULL + imag_pos: object = NULL + / + * + real as r: object = NULL + imag as i: object = NULL Create a complex number from a string or numbers. @@ -1204,8 +1202,9 @@ with the specified real and imaginary components. [clinic start generated code]*/ static PyObject * -complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i) -/*[clinic end generated code: output=b6c7dd577b537dc1 input=ff4268dc540958a4]*/ +complex_new_impl(PyTypeObject *type, PyObject *real_pos, PyObject *imag_pos, + PyObject *r, PyObject *i) +/*[clinic end generated code: output=fdc6ecf8914112b7 input=09930f0cd44fd3a8]*/ { PyObject *tmp; PyNumberMethods *nbr, *nbi = NULL; @@ -1214,7 +1213,30 @@ complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i) int cr_is_complex = 0; int ci_is_complex = 0; + /* See the comment before complex_from_arg(). */ + if (real_pos != NULL) { + if (r != NULL) { + PyErr_SetString(PyExc_TypeError, "argument for complex() given " + "by name ('real') and position (1)"); + return NULL; + } + if (imag_pos == NULL && i == NULL) { + return complex_from_arg(type, real_pos); + } + r = real_pos; + } + if (imag_pos != NULL) { + if (i != NULL) { + PyErr_SetString(PyExc_TypeError, "argument for complex() given " + "by name ('imag') and position (2)"); + return NULL; + } + i = imag_pos; + } if (r == NULL) { + if (i == NULL) { + return complex_subtype_from_doubles(type, 0, 0); + } r = _PyLong_GetZero(); } PyObject *orig_r = r; @@ -1454,7 +1476,8 @@ PyTypeObject PyComplex_Type = { 0, /* tp_dictoffset */ 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ - actual_complex_new, /* tp_new */ + complex_new, /* tp_new */ PyObject_Free, /* tp_free */ + .tp_vectorcall = complex_vectorcall, .tp_version_tag = _Py_TYPE_VERSION_COMPLEX, }; From cf5376ced3b1f9ca2ffc71c1422f6cb794c6efb9 Mon Sep 17 00:00:00 2001 From: Cody Maloney Date: Sat, 21 Nov 2026 23:11:42 -0800 Subject: [PATCH 2/2] Match main's error text when complex() gets more than 2 arguments Co-Authored-By: Claude Opus 5.5 --- Lib/test/test_complex.py | 4 +++- Objects/complexobject.c | 11 ++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/Lib/test/test_complex.py b/Lib/test/test_complex.py index 2d220bdeb7cc40..61e4bff039192e 100644 --- a/Lib/test/test_complex.py +++ b/Lib/test/test_complex.py @@ -611,8 +611,10 @@ def check(z, x, y): check(complex(4.25, imag=1.5), 4.25, 1.5) self.assertRaisesRegex(TypeError, r"given by name \('real'\) and position \(1\)", complex, 4.25, real=1.5) - self.assertRaisesRegex(TypeError, r"given by name \('imag'\) and position \(2\)", + self.assertRaisesRegex(TypeError, r"takes at most 2 arguments \(3 given\)", complex, 4.25, 1.5, imag=1.5) + self.assertRaisesRegex(TypeError, r"takes at most 2 arguments \(3 given\)", + complex, 1, 2, real=3) # check that the sign of a zero in the real or imaginary part # is preserved when constructing from two floats. diff --git a/Objects/complexobject.c b/Objects/complexobject.c index 3fc3c4119a52fc..78295e82e744a4 100644 --- a/Objects/complexobject.c +++ b/Objects/complexobject.c @@ -1214,6 +1214,12 @@ complex_new_impl(PyTypeObject *type, PyObject *real_pos, PyObject *imag_pos, int ci_is_complex = 0; /* See the comment before complex_from_arg(). */ + int nargs = (real_pos != NULL) + (imag_pos != NULL) + (r != NULL) + (i != NULL); + if (nargs > 2) { + PyErr_Format(PyExc_TypeError, + "complex() takes at most 2 arguments (%d given)", nargs); + return NULL; + } if (real_pos != NULL) { if (r != NULL) { PyErr_SetString(PyExc_TypeError, "argument for complex() given " @@ -1226,11 +1232,6 @@ complex_new_impl(PyTypeObject *type, PyObject *real_pos, PyObject *imag_pos, r = real_pos; } if (imag_pos != NULL) { - if (i != NULL) { - PyErr_SetString(PyExc_TypeError, "argument for complex() given " - "by name ('imag') and position (2)"); - return NULL; - } i = imag_pos; } if (r == NULL) {