Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 13a6c09

Browse files
bpo-32259: Make a TypeError message when unpack non-iterable more specific. (#4903)
1 parent a8f4e15 commit 13a6c09

5 files changed

Lines changed: 16 additions & 6 deletions

File tree

Lib/test/test_dataclasses.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -866,7 +866,7 @@ class Date:
866866
self.assertNotEqual(Point3D(1, 2, 3), (1, 2, 3))
867867

868868
# Make sure we can't unpack
869-
with self.assertRaisesRegex(TypeError, 'is not iterable'):
869+
with self.assertRaisesRegex(TypeError, 'unpack'):
870870
x, y, z = Point3D(4, 5, 6)
871871

872872
# Maka sure another class with the same field names isn't

Lib/test/test_unpack.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@
5555
>>> a, b, c = 7
5656
Traceback (most recent call last):
5757
...
58-
TypeError: 'int' object is not iterable
58+
TypeError: cannot unpack non-iterable int object
5959
6060
Unpacking tuple of wrong size
6161
@@ -129,7 +129,7 @@
129129
>>> () = 42
130130
Traceback (most recent call last):
131131
...
132-
TypeError: 'int' object is not iterable
132+
TypeError: cannot unpack non-iterable int object
133133
134134
Unpacking to an empty iterable should raise ValueError
135135

Lib/test/test_unpack_ex.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,7 @@
263263
>>> a, *b = 7
264264
Traceback (most recent call last):
265265
...
266-
TypeError: 'int' object is not iterable
266+
TypeError: cannot unpack non-iterable int object
267267
268268
Unpacking sequence too short
269269
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
The error message of a TypeError raised when unpack non-iterable is now more
2+
specific.

Python/ceval.c

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4137,8 +4137,16 @@ unpack_iterable(PyObject *v, int argcnt, int argcntafter, PyObject **sp)
41374137
assert(v != NULL);
41384138

41394139
it = PyObject_GetIter(v);
4140-
if (it == NULL)
4141-
goto Error;
4140+
if (it == NULL) {
4141+
if (PyErr_ExceptionMatches(PyExc_TypeError) &&
4142+
v->ob_type->tp_iter == NULL && !PySequence_Check(v))
4143+
{
4144+
PyErr_Format(PyExc_TypeError,
4145+
"cannot unpack non-iterable %.200s object",
4146+
v->ob_type->tp_name);
4147+
}
4148+
return 0;
4149+
}
41424150

41434151
for (; i < argcnt; i++) {
41444152
w = PyIter_Next(it);

0 commit comments

Comments
 (0)