Skip to content

Commit dc03ce7

Browse files
authored
gh-95144: Improve error message of ... in None (GH-119888)
1 parent 65feded commit dc03ce7

File tree

4 files changed

+18
-5
lines changed

4 files changed

+18
-5
lines changed

Lib/test/test_contains.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,11 @@ def test_common_tests(self):
2424
self.assertNotIn(0, b)
2525
self.assertIn(1, c)
2626
self.assertNotIn(0, c)
27-
self.assertRaises(TypeError, lambda: 1 in a)
28-
self.assertRaises(TypeError, lambda: 1 not in a)
27+
msg = "argument of type 'base_set' is not a container or iterable"
28+
with self.assertRaisesRegex(TypeError, msg):
29+
1 in a
30+
with self.assertRaisesRegex(TypeError, msg):
31+
1 not in a
2932

3033
# test char in string
3134
self.assertIn('c', 'abc')

Lib/test/test_sqlite3/test_dbapi.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1434,7 +1434,7 @@ def test_blob_sequence_not_supported(self):
14341434
self.blob + self.blob
14351435
with self.assertRaisesRegex(TypeError, "unsupported operand"):
14361436
self.blob * 5
1437-
with self.assertRaisesRegex(TypeError, "is not iterable"):
1437+
with self.assertRaisesRegex(TypeError, "is not.+iterable"):
14381438
b"a" in self.blob
14391439

14401440
def test_blob_context_manager(self):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve the error message from ``a in b`` when ``b`` is not a container
2+
to mention the term "container".

Objects/abstract.c

+10-2
Original file line numberDiff line numberDiff line change
@@ -2141,7 +2141,7 @@ PySequence_Fast(PyObject *v, const char *m)
21412141
PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
21422142
PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
21432143
set ValueError and return -1 if none found; also return -1 on error.
2144-
Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2144+
PY_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
21452145
*/
21462146
Py_ssize_t
21472147
_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
@@ -2158,7 +2158,15 @@ _PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
21582158
it = PyObject_GetIter(seq);
21592159
if (it == NULL) {
21602160
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
2161-
type_error("argument of type '%.200s' is not iterable", seq);
2161+
if (operation == PY_ITERSEARCH_CONTAINS) {
2162+
type_error(
2163+
"argument of type '%.200s' is not a container or iterable",
2164+
seq
2165+
);
2166+
}
2167+
else {
2168+
type_error("argument of type '%.200s' is not iterable", seq);
2169+
}
21622170
}
21632171
return -1;
21642172
}

0 commit comments

Comments
 (0)