Skip to content

Commit 0df9822

Browse files
cmaloneyclaude
andcommitted
gh-162258: Use vectorcall for slot wrappers
Add a `vectorcall` member to `PyWrapperDescrObject` so slots which don't require a args tuple or kwargs dict can avoid constructing them. Wrappers which take a keywords dict (`__init__` and `__call__`) keep calling through `tp_call`, as `METH_VARARGS` functions do: with vectorcall, `PyObject_Call()` with `**kwargs` would unpack the dict into an array only for the wrapper to build a new dict. Removing the `PyWrapperFlag_KEYWORDS` check in `PyDescr_NewWrapper()` shows it: `dict.__init__({}, **kw)` goes from 70.6 ns to 99.0 ns. The object grows by one pointer (`sys.getsizeof(object.__init__)`: 72 -> 80 bytes) but stays in the same allocator size class: on the default build, `sys.getallocatedblocks()` and max RSS are unchanged at startup (about 1,000 slot wrappers) and after importing asyncio, json, dataclasses, collections, decimal, typing, re, email and http.client. Results and error messages are unchanged. | Benchmark | main | PR | |---------------------------------|:-------:|:---------------------:| | `c['x'] = 1` | 35.5 ns | 26.6 ns: 1.33x faster | | `int.__add__(1, 2)` | 26.9 ns | 21.5 ns: 1.25x faster | | `object.__setattr__(o, 'x', 1)` | 37.2 ns | 30.8 ns: 1.21x faster | | `frozen_triple(1, 2, 3)` | 156 ns | 132 ns: 1.18x faster | | `dict.__init__({}, **kw)` | 68.9 ns | 70.9 ns: 1.03x slower | `dict_subclass()`, `list_subclass()` and `pair(1, 2)` were not significantly different. `dict_subclass()`, `list_subclass()` and `dict.__init__({}, **kw)` call `__init__`, which takes the same path as before. Across builds of the same code they moved by up to 7 ns either way. Under callgrind, `dict.__init__({}, **kw)` costs about 20 more instructions per call in the call path (the `self` reference and type check); `perf stat` pinned to one core shows no cycle difference for the subclass rows beyond run-to-run variance. Linux x86-64, clang PGO+LTO builds, pyperf: ```python import pyperf runner = pyperf.Runner() setup = """ from collections import Counter from dataclasses import dataclass @DataClass(frozen=True) class frozen_triple: a: int b: int c: int @DataClass class pair: a: int b: int class C: pass class list_subclass(list): def __init__(self): super().__init__() class dict_subclass(dict): def __init__(self): super().__init__(a=1) o = C() c = Counter() kw = {'x': 1} """ for stmt in [ "c['x'] = 1", "object.__setattr__(o, 'x', 1)", "int.__add__(1, 2)", "frozen_triple(1, 2, 3)", "dict_subclass()", "list_subclass()", "dict.__init__({}, **kw)", "pair(1, 2)", ]: runner.timeit(stmt, stmt, setup) ``` Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent e8fb673 commit 0df9822

4 files changed

Lines changed: 65 additions & 12 deletions

File tree

‎Include/cpython/descrobject.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ typedef struct {
5555
PyDescr_COMMON;
5656
struct wrapperbase *d_base;
5757
void *d_wrapped; /* This can be any function pointer */
58+
vectorcallfunc vectorcall;
5859
} PyWrapperDescrObject;
5960

6061
PyAPI_FUNC(PyObject *) PyDescr_NewWrapper(PyTypeObject *,

‎Lib/test/test_descr.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import builtins
22
import copyreg
3+
import functools
34
import gc
45
import itertools
56
import math
@@ -3791,6 +3792,8 @@ def f(a): return a
37913792
bytearray.__init__(ba, 'abc\xbd\u20ac',
37923793
encoding='latin1', errors='replace')
37933794
self.assertEqual(ba, b'abc\xbd?')
3795+
with self.assertRaisesRegex(TypeError, 'takes no keyword arguments'):
3796+
int.__add__(1, 2, x=1)
37943797

37953798
@support.skip_if_huge_c_stack()
37963799
@support.skip_wasi_stack_overflow()
@@ -5201,6 +5204,22 @@ class Foo:
52015204
self.assertRaises(RecursionError, str, foo)
52025205
self.assertRaises(RecursionError, repr, foo)
52035206

5207+
def test_slot_wrapper_holds_self(self):
5208+
# Make sure wrapper takes a strong reference to itself when called.
5209+
# cmp_to_key() does not own the objects passed to it. Custom list type
5210+
# so we can take a weakref.
5211+
class L(list):
5212+
pass
5213+
class Evil:
5214+
def __eq__(evil, other):
5215+
k.obj = None
5216+
self.assertIsNotNone(wr())
5217+
return True
5218+
K = functools.cmp_to_key(list.__eq__)
5219+
k = K(L([Evil()]))
5220+
wr = weakref.ref(k.obj)
5221+
k < K([1])
5222+
52045223
def test_mixing_slot_wrappers(self):
52055224
class X(dict):
52065225
__setattr__ = dict.__setitem__

‎Lib/test/test_sys.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1772,7 +1772,7 @@ def inner():
17721772
import collections
17731773
check(collections.defaultdict.default_factory, size('3PP'))
17741774
# wrapper_descriptor (descriptor object)
1775-
check(int.__add__, size('3P2P'))
1775+
check(int.__add__, size('3P3P'))
17761776
# method-wrapper (descriptor object)
17771777
check({}.__iter__, size('2P'))
17781778
# empty dict

‎Objects/descrobject.c‎

Lines changed: 44 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -535,24 +535,22 @@ wrapperdescr_raw_call(PyWrapperDescrObject *descr, PyObject *self,
535535
}
536536

537537
static PyObject *
538-
wrapperdescr_call(PyObject *_descr, PyObject *args, PyObject *kwds)
538+
wrapperdescr_impl(PyObject *_descr, PyObject *const *args,
539+
Py_ssize_t nargs, PyObject *kwds)
539540
{
540541
PyWrapperDescrObject *descr = (PyWrapperDescrObject *)_descr;
541-
Py_ssize_t argc;
542542
PyObject *self, *result;
543543

544544
/* Make sure that the first argument is acceptable as 'self' */
545-
assert(PyTuple_Check(args));
546-
argc = PyTuple_GET_SIZE(args);
547-
if (argc < 1) {
545+
if (nargs < 1) {
548546
PyErr_Format(PyExc_TypeError,
549547
"descriptor '%V' of '%.100s' "
550548
"object needs an argument",
551549
descr_name((PyDescrObject *)descr), "?",
552550
PyDescr_TYPE(descr)->tp_name);
553551
return NULL;
554552
}
555-
self = PyTuple_GET_ITEM(args, 0);
553+
self = args[0];
556554
if (!_PyObject_RealIsSubclass((PyObject *)Py_TYPE(self),
557555
(PyObject *)PyDescr_TYPE(descr))) {
558556
PyErr_Format(PyExc_TypeError,
@@ -565,12 +563,41 @@ wrapperdescr_call(PyObject *_descr, PyObject *args, PyObject *kwds)
565563
return NULL;
566564
}
567565

568-
args = PyTuple_GetSlice(args, 1, argc);
569-
if (args == NULL) {
566+
PyObject *argstuple = PyTuple_FromArray(args + 1, nargs - 1);
567+
if (argstuple == NULL) {
570568
return NULL;
571569
}
572-
result = wrapperdescr_raw_call(descr, self, args, kwds);
573-
Py_DECREF(args);
570+
/* Turn vectorcall borrowed reference into a strong reference */
571+
Py_INCREF(self);
572+
result = wrapperdescr_raw_call(descr, self, argstuple, kwds);
573+
Py_DECREF(self);
574+
Py_DECREF(argstuple);
575+
return result;
576+
}
577+
578+
static PyObject *
579+
wrapperdescr_call(PyObject *descr, PyObject *args, PyObject *kwds)
580+
{
581+
return wrapperdescr_impl(descr, _PyTuple_ITEMS(args),
582+
PyTuple_GET_SIZE(args), kwds);
583+
}
584+
585+
static PyObject *
586+
wrapperdescr_vectorcall(PyObject *descr, PyObject *const *args,
587+
size_t nargsf, PyObject *kwnames)
588+
{
589+
PyThreadState *tstate = _PyThreadState_GET();
590+
Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
591+
if (kwnames != NULL && PyTuple_GET_SIZE(kwnames) > 0) {
592+
/* These wrappers take no keywords: let tp_call raise */
593+
return _PyObject_MakeTpCall(tstate, descr, args, nargs, kwnames);
594+
}
595+
PyObject *result = NULL;
596+
if (!_Py_EnterRecursiveCallTstate(tstate,
597+
" while calling a Python object")) {
598+
result = wrapperdescr_impl(descr, args, nargs, NULL);
599+
_Py_LeaveRecursiveCallTstate(tstate);
600+
}
574601
return result;
575602
}
576603

@@ -881,7 +908,7 @@ PyTypeObject PyWrapperDescr_Type = {
881908
sizeof(PyWrapperDescrObject),
882909
0,
883910
descr_dealloc, /* tp_dealloc */
884-
0, /* tp_vectorcall_offset */
911+
offsetof(PyWrapperDescrObject, vectorcall), /* tp_vectorcall_offset */
885912
0, /* tp_getattr */
886913
0, /* tp_setattr */
887914
0, /* tp_as_async */
@@ -896,6 +923,7 @@ PyTypeObject PyWrapperDescr_Type = {
896923
0, /* tp_setattro */
897924
0, /* tp_as_buffer */
898925
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
926+
Py_TPFLAGS_HAVE_VECTORCALL |
899927
Py_TPFLAGS_METHOD_DESCRIPTOR, /* tp_flags */
900928
0, /* tp_doc */
901929
descr_traverse, /* tp_traverse */
@@ -1030,6 +1058,11 @@ PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *base, void *wrapped)
10301058
if (descr != NULL) {
10311059
descr->d_base = base;
10321060
descr->d_wrapped = wrapped;
1061+
/* Like METH_VARARGS functions, wrappers taking a keywords dict
1062+
(__init__, __call__) are faster through tp_call */
1063+
if (!(base->flags & PyWrapperFlag_KEYWORDS)) {
1064+
descr->vectorcall = wrapperdescr_vectorcall;
1065+
}
10331066
}
10341067
return (PyObject *)descr;
10351068
}

0 commit comments

Comments
 (0)