]> granicus.if.org Git - python/commitdiff
#19449: Handle non-string keys when generating 'fieldnames' error.
authorR David Murray <rdmurray@bitdance.com>
Tue, 19 Nov 2013 18:16:20 +0000 (13:16 -0500)
committerR David Murray <rdmurray@bitdance.com>
Tue, 19 Nov 2013 18:16:20 +0000 (13:16 -0500)
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).

Lib/csv.py
Lib/test/test_csv.py
Misc/NEWS

index da3bc44e7acc0fb6556a3ca3799dc638dbe8f5b0..a56eed88c862d4a43cbbcf10b5603ffb327badcc 100644 (file)
@@ -146,7 +146,7 @@ class DictWriter:
             wrong_fields = [k for k in rowdict if k not in self.fieldnames]
             if wrong_fields:
                 raise ValueError("dict contains fields not in fieldnames: "
-                                 + ", ".join(wrong_fields))
+                                 + ", ".join([repr(x) for x in wrong_fields]))
         return [rowdict.get(key, self.restval) for key in self.fieldnames]
 
     def writerow(self, rowdict):
index 976e6205b71ab6b96ccd89db12d0a088bd7e8906..479ebd9bf223d548aeeba6fc84a7c1870cfa7fce 100644 (file)
@@ -570,6 +570,18 @@ class TestDictFields(unittest.TestCase):
         fileobj = StringIO()
         self.assertRaises(TypeError, csv.DictWriter, fileobj)
 
+    def test_write_fields_not_in_fieldnames(self):
+        with TemporaryFile("w+", newline='') as fileobj:
+            writer = csv.DictWriter(fileobj, fieldnames = ["f1", "f2", "f3"])
+            # Of special note is the non-string key (issue 19449)
+            with self.assertRaises(ValueError) as cx:
+                writer.writerow({"f4": 10, "f2": "spam", 1: "abc"})
+            exception = str(cx.exception)
+            self.assertIn("fieldnames", exception)
+            self.assertIn("'f4'", exception)
+            self.assertNotIn("'f2'", exception)
+            self.assertIn("1", exception)
+
     def test_read_dict_fields(self):
         with TemporaryFile("w+") as fileobj:
             fileobj.write("1,2,abc\r\n")
index 897bbc23d7acb9f63c0ab700bfdad0eee469b57e..4278e952f54f31a2779c6ba9a602ecc6f99346a5 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -13,6 +13,9 @@ Core and Builtins
 Library
 -------
 
+- Issue #19449: in csv's writerow, handle non-string keys when generating the
+  error message that certain keys are not in the 'fieldnames' list.
+
 - Fix test.support.bind_port() to not cause an error when Python was compiled
   on a system with SO_REUSEPORT defined in the headers but run on a system
   with an OS kernel that does not support that reasonably new socket option.