question 279 Data Models & Typing · medium
Export to anything that can write
A report exporter shouldn't care whether it writes to a file, to memory or to a network stream. Write a Protocol Writer describing what the exporter needs, write(text: str) -> int (return the number of characters written, as files do), and export_csv(rows, writer), which writes a header line and one line per row through writer.write and returns the total number of characters written.
Protocol
class Writer(Protocol) with write(self, text: str) -> intFunction
export_csv(rows: list[dict[str, object]], writer: Writer) -> intOutputheader from the first row's keys; values joined with
,; every line ends with \n; no rows → nothing written, returns 0Works with
io.StringIO() and any class of your own with a matching write