Skip to content

ADR 0061: Files and standard input

Status: Final Type: Feature Created: 2026-10-13 Amends: 0024 (a temporary is released where its statement ends) Related-ADRs: 0059 (the standard library, compiled where CPython is reproduced exactly), 0024 (the count that closes a file), 0007 (the exceptions a file operation raises), 0015 (the bytes binary mode returns). Provenance: A145, the Shed Skin census (notes/measurements.md, 2026-10-13).

Context

In the census, files stand in front of 20 of the 53 Shed Skin programs. They read a data file (open(path).read(), readlines(), for line in open(path), a comprehension over one), write an image or a log (print(..., file=out), out.write(s)), and read standard input (input(), sys.stdin.read(1), sys.stdin.readline()). postpile refused open as an unknown function and print(..., file=) as a keyword it did not lower.

CPython's io module defines what a file does. Most of it is reproducible exactly: the bytes on disk, the text read back, newline translation, the exceptions and their messages. This ADR draws the line around the two parts that are not. One is how far a write has reached the disk before the file is closed or released, which depends on CPython's buffer sizes. The other is the position a decoding error reports, which depends on how CPython chunks its input.

Decision

A file is an instance of the class TextIOWrapper, CPython's name for it, shared across a program's modules. It has no fields a program can see and no methods: an operation on it is a call into a dedicated runtime unit (pp_file), linked by all three backends when a program uses one. Because it is an instance, everything that holds instances holds it with no new rule: a field, a list element, a parameter, a return value, a release. The block has three slots: the FILE *, the mode, and the path it was opened with. Its descriptor gives the stream the kind F: the object runtime closes the stream when the last reference goes, which is when CPython's reference count closes it. So the file closes where CPython closes it when f = open(p, "w") is rebound, when an instance holding it is released, and when a frame returns. A file is the first instance whose release is observable, directly or through an instance that holds one. A fresh instance is parked in a temporary slot keyed by its site. In every module, the slot drops its reference when the statement ends, as CPython drops the temporary. So a = open(p, "w") rebound closes the first file at the rebinding, and so does a Log(path) rebound or cleared. The file a for loop iterates is dropped when the loop ends. typing.TextIO, mypy's spelling, names the type in an annotation.

open(path, mode, encoding=...), in text mode, UTF-8, or in binary mode:

  • the mode is a literal, so that the file's type is known: r, w, a and x, each with t or b or neither. A mode CPython refuses is refused with that reason (t with b, or encoding= with b, is CPython's ValueError);
  • encoding= is accepted when it is a literal spelling of UTF-8; another encoding, newline=, errors= and buffering are refused;
  • open performs CPython's sequence: open(2) with O_CLOEXEC, then fstat, so that a directory opened for reading raises IsADirectoryError at open, as in CPython;
  • a failure raises the OSError subclass CPython chooses for the errno (FileNotFoundError, FileExistsError, IsADirectoryError, NotADirectoryError, PermissionError, otherwise OSError), with CPython's message, [Errno 2] No such file or directory: 'path', the path as its repr. The vocabulary gains those six names and EOFError. An errno whose subclass the vocabulary does not have (TimeoutError, BlockingIOError and the connection errors, none of which open raises on a local file) stops the program with a message, since any class it could raise would be the wrong one;
  • a path with a NUL is CPython's ValueError: embedded null byte.

Reading follows CPython's text layer. read(), read(n) in characters, readline() and readlines(); a file open returns translates \r\n and \r to \n, and sys.stdin does not, since CPython's standard input ends lines at \n only and keeps the \r. for line in f is readline() until it returns "", written as the while loop it is, so a body that reads the file itself gets the next line, and else, break and continue keep their meaning. A comprehension over a file lowers to that loop, like any comprehension.

Binary mode (rb, wb, ab, xb) returns a binary file, a separate class (BinaryIO, mypy's name for the type) on the same block, with the mode flagged so that the runtime's read and write checks hold for it unchanged. read() and read(n) on it return the bytes on disk (0015), with no decoding and no newline translation; write(b) takes a bytes and returns the count. close(), with, a temporary closed at the end of the statement and the OSError family behave as for a text file. The file unit builds and inspects bytes values, so a program that links it links the bytes unit too.

The repr of a binary file is io's: <_io.BufferedReader name='in.jpg'> for a binary file opened to read, <_io.BufferedWriter name='out.bmp'> for one opened to write or append, the same whether the file is open or closed. The file block keeps a third slot, the path it was opened with, a counted str released with the file; __pp_file_repr writes the text, the name by str's repr (whose non-ASCII stop, A12, applies). print, str, repr, %s and an f-string all reach it. A text file's repr is refused: CPython's names the encoding, which is the locale's when open is given none and changes with UTF-8 mode, so a compiled program cannot know it.

Writing: write(s) returns the number of characters, as CPython's text stream does. print(..., file=f) is what CPython's print does, piece by piece: all arguments are evaluated first, then write(str(arg)) per argument with sep between and end last, so a piece written before a later str raises stays written. file= takes a name or an attribute of one, which evaluating early changes nothing; file=None is stdout.

Closing: close() is idempotent. A read or a write on a closed file raises ValueError: I/O operation on closed file.. with open(...) as f: binds the file, runs the body and closes it on the way out, normal or raising, which is its __exit__; several items nest. open(p).read(), a file nothing names, is closed right after the call, which is when CPython's count releases it, so open(p, "w").write(s) followed by a read of p sees what was written.

Standard input: sys.stdin.read(), read(n), readline(), readlines() and for line in sys.stdin; input(prompt) writes str(prompt), flushes stdout, reads a line, strips the \n, and raises EOFError("EOF when reading a line") when the input ended before anything was read. Both are compiled into an executable only: in a host process standard input is CPython's, with a buffer that a second reader would split.

Stopped rather than raised, each with a message on stderr, because raising them would be wrong in a way the program could observe:

  • io.UnsupportedOperation (a read on a file opened for writing, or the reverse) is both an OSError and a ValueError in CPython. A vocabulary of single parents cannot say that, and making it an OSError would let except ValueError: miss it;
  • text that is not UTF-8. CPython raises UnicodeDecodeError at a byte position that depends on its buffering, which this runtime does not reproduce. A NUL in text is refused for bytes.decode's reason (ADR 0015): a Str cannot hold one;
  • copy.copy or copy.deepcopy of a file reached through a structure. CPython raises TypeError: cannot pickle 'TextIOWrapper' instances, which the compiler raises as a refusal where it sees the file itself.

Refused, each with its reason: iterating a binary file and calling readline on it, since their lines are bytes. An encoding other than UTF-8, newline=, errors= and buffering are refused too, since this runtime does not reproduce their effects. The other operations a file has in CPython are listed on the compatibility page until they are lowered.

Consequences

  • One residue is not reproduced: a program that reads a file while another handle on it holds unflushed writes, without closing or flushing that handle, sees whatever the buffers have let through. CPython's answer depends on its buffer sizes, this one on stdio's. Closing, releasing, with and the end of a statement over an unnamed file all flush, as they do in CPython, so a program has to hold two handles on one file to meet it.
  • A file is held wherever an instance is: a field assigned from open(...) or from a parameter annotated TextIO, a list element, a return value.

Alternatives considered

  • A file as a new counted type, with a dedicated wire type in the IR and the backends: the representation the other counted types have. It would have cost an IR type, accessors on three backends and entries in the containers' kind tables, to say what an instance already says. The one thing an instance did not have, a stream to close on release, is one character in the descriptor.
  • Materializing for line in f as readlines(): no new loop shape, and wrong for a body that reads the same file, which CPython lets interleave with the iteration.
  • Unbuffered writes, so that a second reader always sees everything written: as different from CPython as a larger buffer, in the other direction.