Skip to content
Open
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
27 changes: 27 additions & 0 deletions Lib/test/test_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,33 @@ def test_roundtrip_escaped_unquoted_newlines(self):
self.assertEqual(row, rows[i])


def test_reader_reentrant_iterator(self):
# gh-145105: re-entering the reader from the iterator must not crash.
class ReentrantIter:
def __init__(self):
self.reader = None
self.n = 0
def __iter__(self):
return self
def __next__(self):
self.n += 1
if self.n == 1:
try:
next(self.reader)
except StopIteration:
pass
return "a,b"
if self.n == 2:
return "x"
raise StopIteration

it = ReentrantIter()
reader = csv.reader(it)
it.reader = reader
with self.assertRaises(csv.Error):
next(reader)


class TestDialectRegistry(unittest.TestCase):
def test_registry_badargs(self):
self.assertRaises(TypeError, csv.list_dialects, None)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix crash in :mod:`csv` reader when iterating with a re-entrant iterator
that calls :func:`next` on the same reader from within ``__next__``.
6 changes: 6 additions & 0 deletions Modules/_csv.c
Original file line number Diff line number Diff line change
Expand Up @@ -961,6 +961,12 @@ Reader_iternext_lock_held(PyObject *op)
Py_DECREF(lineobj);
return NULL;
}
if (self->fields == NULL) {
PyErr_SetString(module_state->error_obj,
"iterator has already advanced the reader");
Py_DECREF(lineobj);
return NULL;
}
++self->line_num;
kind = PyUnicode_KIND(lineobj);
data = PyUnicode_DATA(lineobj);
Expand Down
Loading