Skip to content

gh-162350: Use AC vectorcall for itertools.product / zip_longest - #162663

Open
tanloong wants to merge 7 commits into
python:mainfrom
tanloong:product_ziplongest_vectorcall
Open

tanloong wants to merge 7 commits into
python:mainfrom
tanloong:product_ziplongest_vectorcall

Conversation

@tanloong

@tanloong tanloong commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Replace hand-written constructors with AC + vectorcall.

product(..., repeat=1, bad='a') now raises TypeError: got an unexpected keyword argument 'bad' instead of TypeError: takes at most 1 keyword argument (2 given); product(..., repeat=-1) now raises ValueError: repeat cannot be negativeinstead ofValueError: repeat argument cannot be negative`.

zip_longest(..., bad='a') now raises TypeError: zip_longest() got an unexpected keyword argument 'bad' instead of TypeError: zip_longest() got an unexpected keyword argument. Other error text for bad argument is unchanged.

Benchmark:

+----------------+--------+----------------------+
| Benchmark      | main   | patch                |
+================+========+======================+
| product(x)     | 215 ns | 177 ns: 1.22x faster |
+----------------+--------+----------------------+
| zip_longest(x) | 221 ns | 194 ns: 1.14x faster |
+----------------+--------+----------------------+
| Geometric mean | (ref)  | 1.18x faster         |
+----------------+--------+----------------------+
Details
import pyperf

SETUP = """
import itertools
x = [1, 2, 3]
"""

CASES = [
    ('product(x)', 'itertools.product(x)'),
    ('zip_longest(x)', 'itertools.zip_longest(x)')
]

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

Comment thread Modules/itertoolsmodule.c Outdated
"repeat argument cannot be negative");
return NULL;
}
if (repeat < 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.

Lets move this check into AC. Py_ssize_t converter has an allow_negative option.

repeat: Py_ssize_t(allow_negative=False) = 1

@tanloong tanloong Nov 28, 2026 •

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.

Updated to use allow_negative. Now raises ValueError: repeat cannot be negative instead of ValueError: repeat argument cannot be negative for negative repeat, added in PR description.

Comment thread Modules/itertoolsmodule.c
for (i=0; i < tuplesize; i++) {
PyObject *item = PyTuple_GET_ITEM(args, i);
PyObject *item = iterables[i];
PyObject *it = PyObject_GetIter(item);

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.

this can run arbitrary code, need to make sure to turn fillvalue into a strong reference from a borrowed reference:

import functools, itertools
class Evil:
    def __iter__(self):
        p.keywords.clear()          # drops the only ref to fillvalue
        return iter([1])
p = functools.partial(itertools.zip_longest, fillvalue=object())
list(p(Evil(), [1, 2, 3]))

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.

Added strong reference of fillvalue; route early returns through error; release fillvalue, ittuple, and result at error.

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.

@rhettinger: ^ See the code above which segfaults without the additional reference counting

(functools.partial also has refcount bugs, which is what makes this visible in python. Generally it should be only visible in C API calling C API)

@rhettinger rhettinger self-assigned this Nov 29, 2026
@rhettinger

Copy link
Copy Markdown
Contributor

There is redundant refcounting. lz->fillvalue = Py_NewRef(fillvalue); Py_XDECREF(fillvalue) takes a reference and immediately drops one. Transferring the reference already held lz->fillvalue = fillvalue is simpler. Also, the X form is unnecessary. fillvalue defaults to Py_None and is never NULL, so the usual Py_INCREF/Py_DECREF will suffice.

Again, the strong reference seems necessary. We don't do it elsewhere and there are no tests to prove that it is needed.

The other itertools vectorcall PR also changes the clinic checksum, so this one will need to be updated once the other PR goes in.

@cmaloney

Copy link
Copy Markdown
Contributor

The extra reference counting is needed. This is the "Thin Ice" (https://docs.python.org/3/extending/extending.html#thin-ice) case in the docs. The other AC Vectorcall conversions which can invoke arbitrary python also make sure to take strong references before invoking arbitray python that could clear the borrowewd references.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants