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
13 changes: 13 additions & 0 deletions Lib/test/test_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -1280,6 +1280,19 @@ class mydialect(csv.Dialect):
self.assertRaises(ValueError, create_invalid, field_name, " ",
skipinitialspace=True)

def test_dialect_getattr_non_attribute_error_propagates(self):
# gh-145966: non-AttributeError exceptions raised by __getattr__
# during dialect attribute lookup must propagate, not be silenced.
class BadDialect:
def __getattr__(self, name):
raise RuntimeError("boom")

with self.assertRaises(RuntimeError):
csv.reader([], dialect=BadDialect())

with self.assertRaises(RuntimeError):
csv.writer(StringIO(), dialect=BadDialect())


class TestSniffer(unittest.TestCase):
sample1 = """\
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Non-:exc:`AttributeError` exceptions raised during dialect attribute lookup
in :mod:`csv` are no longer silently suppressed.
20 changes: 13 additions & 7 deletions Modules/_csv.c
Original file line number Diff line number Diff line change
Expand Up @@ -497,13 +497,19 @@ dialect_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
Py_XINCREF(skipinitialspace);
Py_XINCREF(strict);
if (dialect != NULL) {
#define DIALECT_GETATTR(v, n) \
do { \
if (v == NULL) { \
v = PyObject_GetAttrString(dialect, n); \
if (v == NULL) \
PyErr_Clear(); \
} \
#define DIALECT_GETATTR(v, n) \
do { \
if (v == NULL) { \
v = PyObject_GetAttrString(dialect, n); \
if (v == NULL) { \
if (PyErr_ExceptionMatches(PyExc_AttributeError)) { \
PyErr_Clear(); \
} \
else { \
goto err; \
} \
} \
} \
Comment on lines +500 to +512
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
#define DIALECT_GETATTR(v, n) \
do { \
if (v == NULL) { \
v = PyObject_GetAttrString(dialect, n); \
if (v == NULL) { \
if (PyErr_ExceptionMatches(PyExc_AttributeError)) { \
PyErr_Clear(); \
} \
else { \
goto err; \
} \
} \
} \
#define DIALECT_GETATTR(v, n) \
do { \
if (v == NULL) { \
if (PyObject_GetOptionalAttrString(dialect, n, &v) < 0) { \
goto err; \
} \
} \

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@encukou Something like that?

} while (0)
DIALECT_GETATTR(delimiter, "delimiter");
DIALECT_GETATTR(doublequote, "doublequote");
Expand Down
Loading