Skip to content

gh-116436: Improve error message when TypeError occurs during dict update #116443

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 7 commits into from
Apr 30, 2025
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