Skip to content

Commit a5b9599

Browse files
committed
#17080: improve error message of float/complex when the wrong type is passed.
1 parent d0786a1 commit a5b9599

File tree

4 files changed

+11
-6
lines changed

4 files changed

+11
-6
lines changed

Lib/test/test_complex.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,7 @@ def split_zeros(x):
303303
self.assertRaises(TypeError, float, 5+3j)
304304
self.assertRaises(ValueError, complex, "")
305305
self.assertRaises(TypeError, complex, None)
306+
self.assertRaisesRegex(TypeError, "not 'NoneType'", complex, None)
306307
self.assertRaises(ValueError, complex, "\0")
307308
self.assertRaises(ValueError, complex, "3\09")
308309
self.assertRaises(TypeError, complex, "1", "2")

Lib/test/test_float.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ def test_float(self):
4141
self.assertRaises(ValueError, float, "-.")
4242
self.assertRaises(ValueError, float, b"-")
4343
self.assertRaises(TypeError, float, {})
44+
self.assertRaisesRegex(TypeError, "not 'dict'", float, {})
4445
# Lone surrogate
4546
self.assertRaises(UnicodeEncodeError, float, '\uD8F0')
4647
# check that we don't accept alternate exponent markers

Objects/complexobject.c

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -773,8 +773,9 @@ complex_subtype_from_string(PyTypeObject *type, PyObject *v)
773773
goto error;
774774
}
775775
else if (PyObject_AsCharBuffer(v, &s, &len)) {
776-
PyErr_SetString(PyExc_TypeError,
777-
"complex() argument must be a string or a number");
776+
PyErr_Format(PyExc_TypeError,
777+
"complex() argument must be a string or a number, not '%.200s'",
778+
Py_TYPE(v)->tp_name);
778779
return NULL;
779780
}
780781

@@ -953,8 +954,9 @@ complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
953954
nbi = i->ob_type->tp_as_number;
954955
if (nbr == NULL || nbr->nb_float == NULL ||
955956
((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
956-
PyErr_SetString(PyExc_TypeError,
957-
"complex() argument must be a string or a number");
957+
PyErr_Format(PyExc_TypeError,
958+
"complex() argument must be a string or a number, not '%.200s'",
959+
Py_TYPE(r)->tp_name);
958960
if (own_r) {
959961
Py_DECREF(r);
960962
}

Objects/floatobject.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,8 +144,9 @@ PyFloat_FromString(PyObject *v)
144144
}
145145
}
146146
else if (PyObject_AsCharBuffer(v, &s, &len)) {
147-
PyErr_SetString(PyExc_TypeError,
148-
"float() argument must be a string or a number");
147+
PyErr_Format(PyExc_TypeError,
148+
"float() argument must be a string or a number, not '%.200s'",
149+
Py_TYPE(v)->tp_name);
149150
return NULL;
150151
}
151152
last = s + len;

0 commit comments

Comments
 (0)