Fix resource leaks caused by buffered readers

Spotted running 'just test -Wall' on the LLM project.
This commit is contained in:
Simon Willison 2026-09-22 11:34:27 -07:00
commit 6bc1d33d58
2 changed files with 75 additions and 1 deletions

View file

@ -380,10 +380,14 @@ def rows_from_file(
"rows_from_file() requires a file-like object that supports peek(), such as io.BytesIO"
)
if not first_bytes:
buffered.close()
return (), Format.CSV
if first_bytes.startswith((b"[", b"{")):
# JSON is read eagerly, so the detection wrapper can close now,
# including when parsing raises an error.
# TODO: Detect newline-JSON
return rows_from_file(buffered, format=Format.JSON)
with buffered:
return rows_from_file(buffered, format=Format.JSON)
else:
dialect = csv.Sniffer().sniff(
first_bytes.decode(encoding or "utf-8-sig", "ignore")