Skip to content

bpo-44512: Fix handling of extrasactions arg with mixed or upper case #26924

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Lib/csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ def __init__(self, f, fieldnames, restval="", extrasaction="raise",
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
Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -762,13 +762,21 @@ def test_write_field_not_in_field_names_raise(self):
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")
dictrow = {'f0': 0, 'f1': 1, 'f2': 2, 'f3': 3}
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()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fixes inconsistent handling of case sensitivity of *extrasaction* arg in
:class:`csv.DictWriter`.