Skip to content

bpo-32255: Fix inconsistent behavior when csv.writer writes None #4769

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 6 commits into from
Dec 12, 2017
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
21 changes: 20 additions & 1 deletion Lib/test/test_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,10 +207,29 @@ def write(self, buf):
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj)
self.assertRaises(TypeError, writer.writerows, None)
writer.writerows([['a','b'],['c','d']])
writer.writerows([['a', 'b'], ['c', 'd']])
fileobj.seek(0)
self.assertEqual(fileobj.read(), "a,b\r\nc,d\r\n")

def test_writerows_with_none(self):
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj)
writer.writerows([['a', None], [None, 'd']])
fileobj.seek(0)
self.assertEqual(fileobj.read(), "a,\r\n,d\r\n")

with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj)
writer.writerows([[None], ['a']])
fileobj.seek(0)
self.assertEqual(fileobj.read(), '""\r\na\r\n')

with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj)
writer.writerows([['a'], [None]])
fileobj.seek(0)
self.assertEqual(fileobj.read(), 'a\r\n""\r\n')

@support.cpython_only
def test_writerows_legacy_strings(self):
import _testcapi
Expand Down
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -1554,6 +1554,7 @@ Joel Taddei
Arfrever Frehtes Taifersar Arahesis
Hideaki Takahashi
Takase Arihiro
Licht Takeuchi
Indra Talip
Neil Tallim
Geoff Talvola
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
A single empty field is now always quoted when written into a CSV file.
This allows to distinguish an empty row from a row consisting of a single empty field.
Patch by Licht Takeuchi.
2 changes: 1 addition & 1 deletion Modules/_csv.c
Original file line number Diff line number Diff line change
Expand Up @@ -1238,7 +1238,7 @@ csv_writerow(WriterObj *self, PyObject *seq)
if (PyErr_Occurred())
return NULL;

if (self->num_fields > 0 && self->rec_size == 0) {
if (self->num_fields > 0 && self->rec_len == 0) {
if (dialect->quoting == QUOTE_NONE) {
PyErr_Format(_csvstate_global->error_obj,
"single empty field record must be quoted");
Expand Down