Skip to content
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
25 changes: 25 additions & 0 deletions Lib/test/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,31 @@ def __next__(self):

self.assertRaises(ValueError, {}.update, [(1, 2, 3)])

def test_update_type_error(self):
with self.assertRaises(TypeError) as cm:
{}.update([object() for _ in range(3)])

self.assertEqual(str(cm.exception), "object is not iterable")
self.assertEqual(
cm.exception.__notes__,
['Cannot convert dictionary update sequence element #0 to a sequence'],
)

def badgen():
yield "key"
raise TypeError("oops")
yield "value"

with self.assertRaises(TypeError) as cm:
dict([badgen() for _ in range(3)])

self.assertEqual(str(cm.exception), "oops")
self.assertEqual(
cm.exception.__notes__,
['Cannot convert dictionary update sequence element #0 to a sequence'],
)


def test_fromkeys(self):
self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
d = {}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improve error message when :exc:`TypeError` occurs during :meth:`dict.update`
9 changes: 5 additions & 4 deletions Objects/dictobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -3706,13 +3706,14 @@ merge_from_seq2_lock_held(PyObject *d, PyObject *seq2, int override)
}

/* Convert item to sequence, and verify length 2. */
fast = PySequence_Fast(item, "");
fast = PySequence_Fast(item, "object is not iterable");
Copy link
Contributor Author

@hauntsaninja hauntsaninja Mar 6, 2024

Choose a reason for hiding this comment

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

Technically, I guess PyObject_GetIter has a different error message for the edge case where __iter__ exists but returns a non-iterator.

I think nicest thing would be to change PySequence_Fast so that if m is NULL it doesn't clobber the message

if (fast == NULL) {
if (PyErr_ExceptionMatches(PyExc_TypeError))
PyErr_Format(PyExc_TypeError,
"cannot convert dictionary update "
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
_PyErr_FormatNote(
"Cannot convert dictionary update "
"sequence element #%zd to a sequence",
i);
}
goto Fail;
}
n = PySequence_Fast_GET_SIZE(fast);
Expand Down
Loading