Skip to content

Commit fe73509

Browse files
bpo-44630: Fix assertion errors in csv module (GH-27127)
Fix incorrect handling of exceptions when interpreting dialect objects in the csv module. Not clearing exceptions between calls to PyObject_GetAttrString() causes assertion failures in pydebug mode (or with assertions enabled). Add a minimal test that would've caught this (passing None as dialect, or any object that isn't a csv.Dialect subclass, which the csv module allows and caters to, even though it is not documented.) In pydebug mode, the test triggers the assertion failure in the old code. Contributed-By: T. Wouters [Google] (cherry picked from commit 0093876) Co-authored-by: T. Wouters <[email protected]>
1 parent a3d20bf commit fe73509

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

Lib/test/test_csv.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,9 +442,15 @@ class testC(csv.excel):
442442
class testUni(csv.excel):
443443
delimiter = "\u039B"
444444

445+
class unspecified():
446+
# A class to pass as dialect but with no dialect attributes.
447+
pass
448+
445449
csv.register_dialect('testC', testC)
446450
try:
447451
self.compare_dialect_123("1,2,3\r\n")
452+
self.compare_dialect_123("1,2,3\r\n", dialect=None)
453+
self.compare_dialect_123("1,2,3\r\n", dialect=unspecified)
448454
self.compare_dialect_123("1\t2\t3\r\n", testA)
449455
self.compare_dialect_123("1:2:3\r\n", dialect=testB())
450456
self.compare_dialect_123("1|2|3\r\n", dialect='testC')

Modules/_csv.c

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -399,9 +399,14 @@ dialect_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
399399
Py_XINCREF(skipinitialspace);
400400
Py_XINCREF(strict);
401401
if (dialect != NULL) {
402-
#define DIALECT_GETATTR(v, n) \
403-
if (v == NULL) \
404-
v = PyObject_GetAttrString(dialect, n)
402+
#define DIALECT_GETATTR(v, n) \
403+
do { \
404+
if (v == NULL) { \
405+
v = PyObject_GetAttrString(dialect, n); \
406+
if (v == NULL) \
407+
PyErr_Clear(); \
408+
} \
409+
} while (0)
405410
DIALECT_GETATTR(delimiter, "delimiter");
406411
DIALECT_GETATTR(doublequote, "doublequote");
407412
DIALECT_GETATTR(escapechar, "escapechar");
@@ -410,7 +415,6 @@ dialect_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
410415
DIALECT_GETATTR(quoting, "quoting");
411416
DIALECT_GETATTR(skipinitialspace, "skipinitialspace");
412417
DIALECT_GETATTR(strict, "strict");
413-
PyErr_Clear();
414418
}
415419

416420
/* check types and convert to C values */

0 commit comments

Comments
 (0)