runtime
279 / 500
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.

Protocolclass Writer(Protocol) with write(self, text: str) -> int
Functionexport_csv(rows: list[dict[str, object]], writer: Writer) -> int
Outputheader from the first row's keys; values joined with ,; every line ends with \n; no rows → nothing written, returns 0
Works withio.StringIO() and any class of your own with a matching write

Loading your progress…

Export to anything that can write — Python practice · Runtime