Skip to content

Commit 6cc8ac9

Browse files
authored
bpo-40736: Improve the error message for re.search() TypeError (GH-23312)
Include the invalid type in the error message.
1 parent 498383c commit 6cc8ac9

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

Lib/test/test_re.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2104,6 +2104,12 @@ def test_bug_34294(self):
21042104
{'tag': 'foo', 'text': None},
21052105
{'tag': 'foo', 'text': None}])
21062106

2107+
def test_bug_40736(self):
2108+
with self.assertRaisesRegex(TypeError, "got 'int'"):
2109+
re.search("x*", 5)
2110+
with self.assertRaisesRegex(TypeError, "got 'type'"):
2111+
re.search("x*", type)
2112+
21072113

21082114
class PatternReprTests(unittest.TestCase):
21092115
def check(self, pattern, expected):

Modules/_sre.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -389,7 +389,8 @@ getstring(PyObject* string, Py_ssize_t* p_length,
389389

390390
/* get pointer to byte string buffer */
391391
if (PyObject_GetBuffer(string, view, PyBUF_SIMPLE) != 0) {
392-
PyErr_SetString(PyExc_TypeError, "expected string or bytes-like object");
392+
PyErr_Format(PyExc_TypeError, "expected string or bytes-like "
393+
"object, got '%.200s'", Py_TYPE(string)->tp_name);
393394
return NULL;
394395
}
395396

0 commit comments

Comments
 (0)