Honour `open()`'s `newline` argument and make file objects iterable

Merged
SA
2mo ago
+867-162

In preparation for csv support.

open() accepts all five newline values with CPython's splitting and translation: None translates \r\n/\r to \n once when the buffer is installed, '' keeps terminators, and '\r'/'\r\n' also translate \n on write while write() reports the length as passed. Binary mode rejects the argument up front; an illegal value raises after the open, as CPython does.

Files are their own iterators: iter(f) is f and __next__ is one readline() from the heap buffer. An unread file is loaded lazily on the first step. ForIter yields the read with a BufferLoad effect and rewinds the instruction pointer so it re-dispatches against the buffer; next() yields with a FileNext effect that owns the default across the yield and answers the call. Consumers that cannot suspend (list(f), enumerate(f), …) raise NotImplementedError until a read or seek() has loaded the buffer, which limitations/open.md records.

Claude-Session: https://claude.ai/code/session_014YiTTzCM85EAg9yP4XQCUC


Summary by cubic

Honours open()'s newline argument with all five values and makes file objects iterable, matching CPython's line splitting, translation, and error behavior.

  • newline=None translates \r\n/\r to \n when the buffer loads; '' keeps terminators; '\r'/'\r\n' also translate \n on write while write() reports the length as passed. Binary mode rejects the argument up front; an illegal value raises after the open, as CPython does.
  • iter(f) is f and each __next__ step is one readline() from the heap buffer. An unread file loads lazily on the first for step or next() call; other consumers (list(f), enumerate(f), …) raise NotImplementedError until a read or seek() has loaded it, now documented in docs/limitations/open.md.
  • A future reply to the load that for or next() waits on raises RuntimeError: file iteration cannot be answered with a future; generator expressions compile to for loops and can load an unread file. The remaining Rust-side consumers will later get a call-boundary retry instead of raising.