https://github.com/python/cpython/commit/35226775926661590e5f2bef8a426c7b7c7ce399
commit: 35226775926661590e5f2bef8a426c7b7c7ce399
branch: main
author: Tan Long <[email protected]>
committer: cmaloney <[email protected]>
date: 2026-11-22T11:35:50-08:00
summary:

gh-162350: Add AC vectorcall for contextvars.ContextVar (#162451)

Replace hand-written `contextvar_tp_new` with Argument Clinic + vectorcall. 

Extra positional arguments now raise `TypeError: ContextVar() takes exactly 1 
positional argument (N given)` instead of `TypeError: ContextVar() takes at 
most 1 positional argument (N given)`.

Benchmark:

```
+--------------------------------+--------+------------------------+
| Benchmark                      | main   | patch                  |
+================================+========+========================+
| ContextVar('x')                | 175 ns | 104 ns: 1.69x faster   |
| contextvars.ContextVar('x')    | 192 ns | 112 ns: 1.72x faster   |
+--------------------------------+--------+------------------------+
| Geometric mean                 | (ref)  | 1.70x faster           |
+--------------------------------+--------+------------------------+
```

```python
import pyperf

SETUP = """
import contextvars
ContextVar = contextvars.ContextVar
"""

CASES = [
    ("ContextVar('x')", "ContextVar('x')"),
    ("contextvars.ContextVar('x')", "contextvars.ContextVar('x')")
]

runner = pyperf.Runner()
for name, stmt in CASES:
    runner.timeit(name, stmt=stmt, setup=SETUP)
```

files:
M Python/clinic/context.c.h
M Python/context.c

diff --git a/Python/clinic/context.c.h b/Python/clinic/context.c.h
index ece7341d65d5fb6..700e2ae3711309d 100644
--- a/Python/clinic/context.c.h
+++ b/Python/clinic/context.c.h
@@ -2,6 +2,10 @@
 preserve
 [clinic start generated code]*/
 
+#if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
+#  include "pycore_gc.h"          // PyGC_Head
+#  include "pycore_runtime.h"     // _Py_ID()
+#endif
 #include "pycore_modsupport.h"    // _PyArg_CheckPositional()
 
 PyDoc_STRVAR(_contextvars_Context_get__doc__,
@@ -116,6 +120,88 @@ _contextvars_Context_copy(PyObject *self, PyObject 
*Py_UNUSED(ignored))
     return _contextvars_Context_copy_impl((PyContext *)self);
 }
 
+static PyObject *
+contextvar_tp_new_impl(PyTypeObject *type, PyObject *name, PyObject *def);
+
+static PyObject *
+contextvar_tp_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)
+
+    #define NUM_KEYWORDS 1
+    static struct {
+        PyGC_Head _this_is_not_used;
+        PyObject_VAR_HEAD
+        Py_hash_t ob_hash;
+        PyObject *ob_item[NUM_KEYWORDS];
+    } _kwtuple = {
+        .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS)
+        .ob_hash = -1,
+        .ob_item = { &_Py_ID(default), },
+    };
+    #undef NUM_KEYWORDS
+    #define KWTUPLE (&_kwtuple.ob_base.ob_base)
+
+    #else  // !Py_BUILD_CORE
+    #  define KWTUPLE NULL
+    #endif  // !Py_BUILD_CORE
+
+    static const char * const _keywords[] = {"", "default", NULL};
+    static _PyArg_Parser _parser = {
+        .keywords = _keywords,
+        .fname = "ContextVar",
+        .kwtuple = KWTUPLE,
+    };
+    #undef KWTUPLE
+    PyObject *argsbuf[2];
+    PyObject * const *fastargs;
+    Py_ssize_t noptargs = nargs + nkw - 1;
+    PyObject *name;
+    PyObject *def = NULL;
+
+    fastargs = _PyArg_UnpackKeywords(args, nargs, kwargs, kwnames, &_parser,
+            /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
+    if (!fastargs) {
+        goto exit;
+    }
+    name = fastargs[0];
+    if (!noptargs) {
+        goto skip_optional_kwonly;
+    }
+    def = fastargs[1];
+skip_optional_kwonly:
+    return_value = contextvar_tp_new_impl(type, name, def);
+
+exit:
+    return return_value;
+}
+
+static PyObject *
+contextvar_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
+{
+    return contextvar_tp_new_helper(type, _PyTuple_CAST(args)->ob_item,
+        PyTuple_GET_SIZE(args),
+        kwargs ? PyDict_GET_SIZE(kwargs) : 0,
+        kwargs, NULL);
+}
+
+static PyObject *
+contextvar_tp_vectorcall(PyObject *type, PyObject *const *args,
+    size_t nargsf, PyObject *kwnames)
+{
+    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
+
+    assert(_PyType_CAST(type)->tp_new == contextvar_tp_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 contextvar_tp_new_helper(_PyType_CAST(type), args, nargs,
+        kwnames ? PyTuple_GET_SIZE(kwnames) : 0,
+        NULL, kwnames);
+}
+
 PyDoc_STRVAR(_contextvars_ContextVar_get__doc__,
 "get($self, default=<unrepresentable>, /)\n"
 "--\n"
@@ -259,4 +345,4 @@ token_exit(PyObject *self, PyObject *const *args, 
Py_ssize_t nargs)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=90ec3e4375804e9b input=a9049054013a1b77]*/
+/*[clinic end generated code: output=488efab9f3932fbb input=a9049054013a1b77]*/
diff --git a/Python/context.c b/Python/context.c
index e4e58df0f96c98f..0d931ef74b56461 100644
--- a/Python/context.c
+++ b/Python/context.c
@@ -994,19 +994,20 @@ class _contextvars.ContextVar "PyContextVar *" 
"&PyContextVar_Type"
 #define _PyContextVar_CAST(op)  ((PyContextVar *)(op))
 
 
+/*[clinic input]
+@vectorcall
+@classmethod
+_contextvars.ContextVar.__new__ as contextvar_tp_new
+    name: object
+    /
+    *
+    default as def: object = NULL
+[clinic start generated code]*/
+
 static PyObject *
-contextvar_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
+contextvar_tp_new_impl(PyTypeObject *type, PyObject *name, PyObject *def)
+/*[clinic end generated code: output=1c8af17a14fc9dc2 input=d5e8cf845a1ddc27]*/
 {
-    static char *kwlist[] = {"", "default", NULL};
-    PyObject *name;
-    PyObject *def = NULL;
-
-    if (!PyArg_ParseTupleAndKeywords(
-            args, kwds, "O|$O:ContextVar", kwlist, &name, &def))
-    {
-        return NULL;
-    }
-
     return (PyObject *)contextvar_new(name, def);
 }
 
@@ -1200,6 +1201,7 @@ PyTypeObject PyContextVar_Type = {
     .tp_traverse = contextvar_tp_traverse,
     .tp_clear = contextvar_tp_clear,
     .tp_new = contextvar_tp_new,
+    .tp_vectorcall = contextvar_tp_vectorcall,
     .tp_free = PyObject_GC_Del,
     .tp_hash = contextvar_tp_hash,
     .tp_repr = contextvar_tp_repr,

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to