X Tutup
Skip to content

Commit fb099c9

Browse files
committed
python#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

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

Lib/csv.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ def _dict_to_list(self, rowdict):
146146
wrong_fields = [k for k in rowdict if k not in self.fieldnames]
147147
if wrong_fields:
148148
raise ValueError("dict contains fields not in fieldnames: "
149-
+ ", ".join(wrong_fields))
149+
+ ", ".join([repr(x) for x in wrong_fields]))
150150
return [rowdict.get(key, self.restval) for key in self.fieldnames]
151151

152152
def writerow(self, rowdict):

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
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ Core and Builtins
1313
Library
1414
-------
1515

16+
- Issue #19449: in csv's writerow, handle non-string keys when generating the
17+
error message that certain keys are not in the 'fieldnames' list.
18+
1619
- Fix test.support.bind_port() to not cause an error when Python was compiled
1720
on a system with SO_REUSEPORT defined in the headers but run on a system
1821
with an OS kernel that does not support that reasonably new socket option.

0 commit comments

Comments
 (0)
X Tutup