[Python-checkins] cpython (3.3): #19449: Handle non-string keys when generating 'fieldnames' error.

r.david.murray python-checkins at python.org
Tue Nov 19 19:25:52 CET 2013


http://hg.python.org/cpython/rev/6e5afeada7ca
changeset:   87272:6e5afeada7ca
branch:      3.3
parent:      87270:4fe87b5df2d0
user:        R David Murray <rdmurray at bitdance.com>
date:        Tue Nov 19 13:16:20 2013 -0500
summary:
  #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).

files:
  Lib/csv.py           |   2 +-
  Lib/test/test_csv.py |  12 ++++++++++++
  Misc/NEWS            |   3 +++
  3 files changed, 16 insertions(+), 1 deletions(-)


diff --git a/Lib/csv.py b/Lib/csv.py
--- a/Lib/csv.py
+++ b/Lib/csv.py
@@ -146,7 +146,7 @@
             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):
diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py
--- a/Lib/test/test_csv.py
+++ b/Lib/test/test_csv.py
@@ -570,6 +570,18 @@
         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")
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -13,6 +13,9 @@
 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.

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list