#19449: Handle non-string keys when generating 'fieldnames' error. · python/cpython@fb099c9 · GitHub
Skip to content

Commit fb099c9

Browse files
committed
#19449: Handle non-string keys when generating 'fieldnames' error.
csv was handling non-string keys fine except for the error message generated when a non-string key was not in 'fieldnames'. Fix by Tomas Grahn, full patch-with-test by Vajrasky Kok (tweaked slightly).
1 parent 30c5ad2 commit fb099c9

3 files changed

Lines changed: 16 additions & 1 deletion

File tree

Lib/csv.py

Lines changed: 1 addition & 1 deletion

Lib/test/test_csv.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -570,6 +570,18 @@ def test_write_no_fields(self):
570570
fileobj = StringIO()
571571
self.assertRaises(TypeError, csv.DictWriter, fileobj)
572572

573+
def test_write_fields_not_in_fieldnames(self):
574+
with TemporaryFile("w+", newline='') as fileobj:
575+
writer = csv.DictWriter(fileobj, fieldnames = ["f1", "f2", "f3"])
576+
# Of special note is the non-string key (issue 19449)
577+
with self.assertRaises(ValueError) as cx:
578+
writer.writerow({"f4": 10, "f2": "spam", 1: "abc"})
579+
exception = str(cx.exception)
580+
self.assertIn("fieldnames", exception)
581+
self.assertIn("'f4'", exception)
582+
self.assertNotIn("'f2'", exception)
583+
self.assertIn("1", exception)
584+
573585
def test_read_dict_fields(self):
574586
with TemporaryFile("w+") as fileobj:
575587
fileobj.write("1,2,abc\r\n")

Misc/NEWS

Lines changed: 3 additions & 0 deletions

0 commit comments

Comments
 (0)