Skip to content

gh-162350: Add AC vectorcall for _csv.Dialect - #162499

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

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

Conversation

@tanloong

@tanloong tanloong commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Replace the hand-written dialect_new with an Argument Clinic + vectorcall. Move _csv_Dialect___replace___impl() from calling dialect_new() to dialect_new_helper() to avoid temporary tuple.

Error message for too many arguments is now TypeError: Dialect() takes at most 9 arguments (N given) instead of TypeError: function takes at most 9 arguments (N given).

Benchmark:

+-------------------------------------------------+---------+-----------------------+
| Benchmark                                       | main    | patch                 |
+=================================================+=========+=======================+
| _csv.Dialect()                                  | 240 ns  | 198 ns: 1.22x faster  |
+-------------------------------------------------+---------+-----------------------+
| _csv.Dialect().__replace__(**{'delimiter':','}) | 1.79 us | 1.55 us: 1.15x faster |
+-------------------------------------------------+---------+-----------------------+
| csv.reader(f)                                   | 409 ns  | 381 ns: 1.07x faster  |
+-------------------------------------------------+---------+-----------------------+
| csv.reader(f, delimiter=';')                    | 803 ns  | 557 ns: 1.44x faster  |
+-------------------------------------------------+---------+-----------------------+
| csv.writer(g)                                   | 399 ns  | 371 ns: 1.08x faster  |
+-------------------------------------------------+---------+-----------------------+
| parse_small()                                   | 5.45 us | 5.07 us: 1.07x faster |
+-------------------------------------------------+---------+-----------------------+
| Geometric mean                                  | (ref)   | 1.14x faster          |
+-------------------------------------------------+---------+-----------------------+

Benchmark hidden because not significant (1): parse_large()
Details
import pyperf

SETUP = """
import _csv, csv, io

f = io.StringIO()
g = io.StringIO()

small_data = "a,b,c\\n" + "1,2,3\\n" * 20        # ~140 bytes
large_data = "a,b,c\\n" + "1,2,3\\n" * 50000    # ~350 KB

def parse_small():
    for row in csv.reader(io.StringIO(small_data), delimiter=','):
        pass

def parse_large():
    for row in csv.reader(io.StringIO(large_data), delimiter=','):
        pass
"""

CASES = [
    ("_csv.Dialect()", "_csv.Dialect()"),
    ("_csv.Dialect().__replace__(**{'delimiter':','})", "_csv.Dialect().__replace__(**{'delimiter':','})"),
    ("csv.reader(f)", "csv.reader(f)"),
    ("csv.reader(f, delimiter=';')", "csv.reader(f, delimiter=';')"),
    ("csv.writer(g)", "csv.writer(g)"),
    ("parse_small()", "parse_small()"),
    ("parse_large()", "parse_large()"),
]

runner = pyperf.Runner()
for name, stmt in CASES:
    runner.timeit(name, stmt=stmt, setup=SETUP)
@tanloong
tanloong marked this pull request as draft November 24, 2026 07:24
@tanloong
tanloong marked this pull request as ready for review November 24, 2026 09:58
Comment thread Modules/_csv.c Resolved

@cmaloney cmaloney left a comment

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.

can you add csv.reader / csv.writer benchmarks here? those are the main thing that gets tested here. Maybe something like csv.reader(f) and csv.reader(f, delimiter=';'). For big CSV files the improvement probably isn't large but I'm okay doing this as long as small / less than 1kb files are faster and large files aren't slower (which I suspect is the case, but best to measure)

@tanloong

Copy link
Copy Markdown
Contributor Author

Added benchmarks of csv.reader(f), csv.reader(f, delimiter=';'), and csv.writer(f) in PR description. Small files are faster and arge files shows no significant difference.

Comment thread Modules/_csv.c

if (dialect != NULL) {
if (PyUnicode_Check(dialect)) {
dialect = get_dialect_from_registry(dialect, module_state);

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 as well as I think the tp_alloc, although that I'm not certain of, can end up calling arbitrary code so need to restructure a bit to ensure the borrowed references aren't invalidated by this. Not sure what is going to be simplest for that, experiment with different options a bit.

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 add strong references before tp_alloc and get_dialect_from_registry. Route early returns through err. Initialize self as NULL to safely Py_CLEAR(self) in err. Add new reference to dialect (ret = Py_NewRef(dialect);) before goto err to safely Py_CLEAR(dialect) in err.

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.

the tp_alloc can't actually run arbitrary python, was a change in 3.15.

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.

Oh. Removed tp_alloc from the comment.

get_dialect_from_registry() calls PyDict_GetItemRef() which can still run arbitrary overloaded __eq__ or __hash__ code when comparing keys.

…r run arbitrary code since 3.15.

`get_dialect_from_registry()` calls `PyDict_GetItemRef()` which can run
arbitrary overloaded `__eq__` or `__hash__` code when comparing keys.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

3 participants