← Back to Pull requests

Implement the `csv` module #1018

Closed
unknown closed this pull request without merging on Oct 16, 2026 15:07 UTC
View on GitHub
unknown unknown commented on Oct 11, 2026 00:26 UTC
Author

Implements the csv module: reader, writer, DictReader, DictWriter, Error, the QUOTE_ constants, the three built-in dialects, get_dialect, list_dialects and a read-only field_size_limit. Stacked on #1001, which it needs for open() files to be iterable.

The parser and writer are ports of CPython's _csv.c state machine and join_append_data, so quoting, escaping, skipinitialspace, strict, the QUOTE_ conversions and the error messages match CPython 3.14. DictReader and DictWriter follow csv.py.

How a file gets read. A reader cannot load an unread open() file from __next__, so csv.reader(f) and csv.DictReader(f) yield the host read with a new LoadThenCall effect and the construction is replayed once the buffer is in place. Every consumer then works: list(csv.reader(f)), next(reader), for row in csv.DictReader(f). The effect is general (it stores a callable plus its ArgValues), so it is also the mechanism the TODO on unloaded_iteration_error describes for list(f) and friends; this PR wires it only for csv.

Writers. writerow returns whatever the target's write() returns, yielding the host write for a file. writerows on a file sends all rows in one host write (WritePosition gained a result_none flag so it still answers None); on any other target write() runs synchronously per row.

Not implemented, documented in limitations/csv.md: register_dialect / unregister_dialect (no module state), Sniffer, changing field_size_limit. The built-in dialects are _csv.Dialect objects rather than classes.

Each commit is one layer: the exception type, the VM effect, the module, tests, type stubs, docs. Note the heap/mod.rs change is two one-line match arms for the new HeapData::Csv payload (GC trace and dec-ref), the same shape as Itertools.

Also touched: _csv.Error crosses the Python and JS bindings as csv.Error; the Type fingerprint in dump_format moved because five variants were appended (additive, no DUMP_VERSION bump).

The four CPython-side case failures in str__format.py, str__percent_format.py, fstring__all.py and bytes__percent_format.py ('{0:.2147482623g}' precision edge cases) also fail when the unchanged test files are run directly under this machine's CPython 3.14.7, so they are unrelated to this branch.

🤖 Generated with Claude Code

https://claude.ai/code/session_01VMK9rG1LtuF1pugGYcHdHC

<!-- This is an auto-generated description by cubic. -->
---

Summary by cubic


Implements the csv module: reader, writer, DictReader, DictWriter, the QUOTE_ constants, the three built-in dialects, get_dialect, list_dialects, Error and a read-only field_size_limit. The parser and writer port CPython's _csv.c state machine, so quoting, escaping, QUOTE_ conversions, underscore digit separators and error messages match CPython 3.14; DictReader/DictWriter follow csv.py. Adds csv.Error (_csv.Error), a direct Exception subclass, as a new exception type across the Python and JS bindings.

Reading files and matching CPython edges

  • reader(f) and DictReader(f) on an unread open() file yield the host read through a new LoadThenCall effect and replay construction once the buffer is in place, so list(...), next(...) and for loops all work; replays ending in an uncaught error get the per-turn resource-limit re-check.

  • writerows on a file sends all rows in one host write; other targets stream rows, polling the clock through a retained iterator view.

  • The writer also polls the clock per 64 KiB chunk of a plain field, so a long ordinary field cannot outrun the time limit.

  • get_dialect(name=...) and field_size_limit(new_limit=...) go through FromArgs, so keyword forms and arity errors match CPython.

  • float() accepts underscore digit separators under CPython's rule, shared with the QUOTE_NONNUMERIC reader.

  • register_dialect, unregister_dialect and Sniffer are absent, field_size_limit is read-only, and the built-in dialects are _csv.Dialect objects rather than classes; the gaps are documented in docs/limitations/csv.md, and hand-written type stubs reject the absent surface up front.
  • Performance work

  • The parser is about a third faster and the writer about a quarter faster: in-place line parsing, one field buffer reused across fields, exact-size allocations, and bulk copies for list/tuple rows and runs of ordinary characters.

  • DictReader takes the field vector straight from the reader and sizes rows by the previous row's key count; DictWriter reads fieldnames, restval and extrasaction per row and shares the dialect through an Arc.

  • Adds read and write benchmarks and limits variants in crates/monty-bench.
  • <sup>Written for commit a43b620944cb6a980c31df286b4c88b9756eb842. Summary will update on new commits.</sup>

    <a href="https://cubic.dev/pr/pydantic/monty/pull/1018?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/pydantic/monty/1018?returnTo=https%3A%2F%2Fgithub.com%2Fpydantic%2Fmonty%2Fpull%2F1018&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>

    <!-- End of auto-generated description by cubic. -->

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: samuelcolvin Review duration: 8080m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #1018"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 56.8% · Lower = rushed or shallow review
    56.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 22.5% · Safe to merge
    22.5%
    Repository