Skip to content

Commit 3522677

Browse files
authored
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) ```
1 parent 0890d65 commit 3522677

2 files changed

Lines changed: 100 additions & 12 deletions

File tree

‎Python/clinic/context.c.h‎

Lines changed: 87 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Python/context.c‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -994,19 +994,20 @@ class _contextvars.ContextVar "PyContextVar *" "&PyContextVar_Type"
994994
#define _PyContextVar_CAST(op) ((PyContextVar *)(op))
995995

996996

997+
/*[clinic input]
998+
@vectorcall
999+
@classmethod
1000+
_contextvars.ContextVar.__new__ as contextvar_tp_new
1001+
name: object
1002+
/
1003+
*
1004+
default as def: object = NULL
1005+
[clinic start generated code]*/
1006+
9971007
static PyObject *
998-
contextvar_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1008+
contextvar_tp_new_impl(PyTypeObject *type, PyObject *name, PyObject *def)
1009+
/*[clinic end generated code: output=1c8af17a14fc9dc2 input=d5e8cf845a1ddc27]*/
9991010
{
1000-
static char *kwlist[] = {"", "default", NULL};
1001-
PyObject *name;
1002-
PyObject *def = NULL;
1003-
1004-
if (!PyArg_ParseTupleAndKeywords(
1005-
args, kwds, "O|$O:ContextVar", kwlist, &name, &def))
1006-
{
1007-
return NULL;
1008-
}
1009-
10101011
return (PyObject *)contextvar_new(name, def);
10111012
}
10121013

@@ -1200,6 +1201,7 @@ PyTypeObject PyContextVar_Type = {
12001201
.tp_traverse = contextvar_tp_traverse,
12011202
.tp_clear = contextvar_tp_clear,
12021203
.tp_new = contextvar_tp_new,
1204+
.tp_vectorcall = contextvar_tp_vectorcall,
12031205
.tp_free = PyObject_GC_Del,
12041206
.tp_hash = contextvar_tp_hash,
12051207
.tp_repr = contextvar_tp_repr,

0 commit comments

Comments
 (0)