bpo-44512: Fix handling of extrasactions arg to csv.DictWriter with mixed or upper case (#26924)

This commit is contained in:
andrei kulakov 2022-12-09 11:14:33 -05:00 committed by GitHub
parent a29a7b9b78
commit d0679c1239
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 12 additions and 1 deletions

View file

@ -139,7 +139,8 @@ class DictWriter:
fieldnames = list(fieldnames)
self.fieldnames = fieldnames # list of keys for the dict
self.restval = restval # for writing short dicts
if extrasaction.lower() not in ("raise", "ignore"):
extrasaction = extrasaction.lower()
if extrasaction not in ("raise", "ignore"):
raise ValueError("extrasaction (%s) must be 'raise' or 'ignore'"
% extrasaction)
self.extrasaction = extrasaction

View file

@ -762,6 +762,10 @@ class TestDictFields(unittest.TestCase):
dictrow = {'f0': 0, 'f1': 1, 'f2': 2, 'f3': 3}
self.assertRaises(ValueError, csv.DictWriter.writerow, writer, dictrow)
# see bpo-44512 (differently cased 'raise' should not result in 'ignore')
writer = csv.DictWriter(fileobj, ['f1', 'f2'], extrasaction="RAISE")
self.assertRaises(ValueError, csv.DictWriter.writerow, writer, dictrow)
def test_write_field_not_in_field_names_ignore(self):
fileobj = StringIO()
writer = csv.DictWriter(fileobj, ['f1', 'f2'], extrasaction="ignore")
@ -769,6 +773,10 @@ class TestDictFields(unittest.TestCase):
csv.DictWriter.writerow(writer, dictrow)
self.assertEqual(fileobj.getvalue(), "1,2\r\n")
# bpo-44512
writer = csv.DictWriter(fileobj, ['f1', 'f2'], extrasaction="IGNORE")
csv.DictWriter.writerow(writer, dictrow)
def test_dict_reader_fieldnames_accepts_iter(self):
fieldnames = ["a", "b", "c"]
f = StringIO()

View file

@ -0,0 +1,2 @@
Fixes inconsistent handling of case sensitivity of *extrasaction* arg in
:class:`csv.DictWriter`.