Skip to content

gh-162350: Add AC vectorcall for operator.itemgetter / attrgetter - #162486

Merged
cmaloney merged 3 commits into
python:mainfrom
tanloong:operator_vectorcall
Nov 28, 2026
Merged

cmaloney merged 3 commits into
python:mainfrom
tanloong:operator_vectorcall

Conversation

@tanloong

@tanloong tanloong commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Replace hand-written itemgetter and attrgetter with Argument Clinic + vectorcall. Rename with as itemgetter_type_new and as attrgetter_type_new to avoid conflict between the generated <name>_vectorcall name and the existing instance-call vectorcall. There is not bad argument message change.

Benchmark:

+-----------------+--------+----------------------+
| Benchmark       | main   | patch                |
+=================+========+======================+
| itemgetter(0)   | 136 ns | 109 ns: 1.25x faster |
+-----------------+--------+----------------------+
| attrgetter("x") | 162 ns | 135 ns: 1.20x faster |
+-----------------+--------+----------------------+
| Geometric mean  | (ref)  | 1.22x faster         |
+-----------------+--------+----------------------+
Details
import pyperf

SETUP = """
import operator
class C:
    x = 1
c = C()
"""

CASES = [
    ('itemgetter(0)', 'operator.itemgetter(0)'),
    ('attrgetter("x")', 'operator.attrgetter("x")')
]

runner = pyperf.Runner()
for name, stmt in CASES:
    runner.timeit(name, stmt=stmt, setup=SETUP)
Comment thread Modules/_operator.c
if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &item))
}
if (items_length == 1) {
item = Py_NewRef(items[0]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

item is now owned and leaks a reference in the error path where PyObject_GC_New fails

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes item now has strong reference. Updated to release it when PyObject_GC_New fails.

`item` has strong reference on both items_length == 1 and items_length > 1 cases. On main branch it has borrowed reference for both.
@cmaloney
cmaloney merged commit a32f37e into python:main Nov 28, 2026
62 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

4 participants