Skip to content

Commit d0679c1

Browse files
authored
bpo-44512: Fix handling of extrasactions arg to csv.DictWriter with mixed or upper case (#26924)
1 parent a29a7b9 commit d0679c1

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

Lib/csv.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,8 @@ def __init__(self, f, fieldnames, restval="", extrasaction="raise",
139139
fieldnames = list(fieldnames)
140140
self.fieldnames = fieldnames # list of keys for the dict
141141
self.restval = restval # for writing short dicts
142-
if extrasaction.lower() not in ("raise", "ignore"):
142+
extrasaction = extrasaction.lower()
143+
if extrasaction not in ("raise", "ignore"):
143144
raise ValueError("extrasaction (%s) must be 'raise' or 'ignore'"
144145
% extrasaction)
145146
self.extrasaction = extrasaction

Lib/test/test_csv.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -762,13 +762,21 @@ def test_write_field_not_in_field_names_raise(self):
762762
dictrow = {'f0': 0, 'f1': 1, 'f2': 2, 'f3': 3}
763763
self.assertRaises(ValueError, csv.DictWriter.writerow, writer, dictrow)
764764

765+
# see bpo-44512 (differently cased 'raise' should not result in 'ignore')
766+
writer = csv.DictWriter(fileobj, ['f1', 'f2'], extrasaction="RAISE")
767+
self.assertRaises(ValueError, csv.DictWriter.writerow, writer, dictrow)
768+
765769
def test_write_field_not_in_field_names_ignore(self):
766770
fileobj = StringIO()
767771
writer = csv.DictWriter(fileobj, ['f1', 'f2'], extrasaction="ignore")
768772
dictrow = {'f0': 0, 'f1': 1, 'f2': 2, 'f3': 3}
769773
csv.DictWriter.writerow(writer, dictrow)
770774
self.assertEqual(fileobj.getvalue(), "1,2\r\n")
771775

776+
# bpo-44512
777+
writer = csv.DictWriter(fileobj, ['f1', 'f2'], extrasaction="IGNORE")
778+
csv.DictWriter.writerow(writer, dictrow)
779+
772780
def test_dict_reader_fieldnames_accepts_iter(self):
773781
fieldnames = ["a", "b", "c"]
774782
f = StringIO()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fixes inconsistent handling of case sensitivity of *extrasaction* arg in
2+
:class:`csv.DictWriter`.

0 commit comments

Comments
 (0)