summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorR David Murray <rdmurray@bitdance.com>2013-11-19 18:17:26 (GMT)
committerR David Murray <rdmurray@bitdance.com>2013-11-19 18:17:26 (GMT)
commit5160da1afc07ab759a95d2b863134a88b9318e65 (patch)
tree5594592d0afa46ea80e4b18569809a284a754578 /Lib
parent0e60f85ce45f119121386adc2527fe66c349b46d (diff)
parentfb099c9ef134166ecaf3905c0d8b2995245f3ded (diff)
downloadcpython-5160da1afc07ab759a95d2b863134a88b9318e65.zip
cpython-5160da1afc07ab759a95d2b863134a88b9318e65.tar.gz
cpython-5160da1afc07ab759a95d2b863134a88b9318e65.tar.bz2
Merge: #19449: Handle non-string keys when generating 'fieldnames' error.
Diffstat (limited to 'Lib')
-rw-r--r--Lib/csv.py2
-rw-r--r--Lib/test/test_csv.py12
2 files changed, 13 insertions, 1 deletions
diff --git a/Lib/csv.py b/Lib/csv.py
index da3bc44..a56eed8 100644
--- a/Lib/csv.py
+++ b/Lib/csv.py
@@ -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):
diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py
index cf0b09c..01fba21 100644
--- a/Lib/test/test_csv.py
+++ b/Lib/test/test_csv.py
@@ -579,6 +579,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")