@@ -274,17 +274,31 @@ PyComplex_ImagAsDouble(PyObject *op)
274274}
275275
276276static PyObject *
277- try_complex_special_method (PyObject * op ) {
277+ try_complex_special_method (PyObject * op )
278+ {
278279 PyObject * f ;
279280 _Py_IDENTIFIER (__complex__ );
280281
281282 f = _PyObject_LookupSpecial (op , & PyId___complex__ );
282283 if (f ) {
283284 PyObject * res = _PyObject_CallNoArg (f );
284285 Py_DECREF (f );
285- if (res != NULL && !PyComplex_Check (res )) {
286- PyErr_SetString (PyExc_TypeError ,
287- "__complex__ should return a complex object" );
286+ if (!res || PyComplex_CheckExact (res )) {
287+ return res ;
288+ }
289+ if (!PyComplex_Check (res )) {
290+ PyErr_Format (PyExc_TypeError ,
291+ "__complex__ returned non-complex (type %.200s)" ,
292+ res -> ob_type -> tp_name );
293+ Py_DECREF (res );
294+ return NULL ;
295+ }
296+ /* Issue #29894: warn if 'res' not of exact type complex. */
297+ if (PyErr_WarnFormat (PyExc_DeprecationWarning , 1 ,
298+ "__complex__ returned non-complex (type %.200s). "
299+ "The ability to return an instance of a strict subclass of complex "
300+ "is deprecated, and may be removed in a future version of Python." ,
301+ res -> ob_type -> tp_name )) {
288302 Py_DECREF (res );
289303 return NULL ;
290304 }
@@ -1030,12 +1044,7 @@ complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i)
10301044 }
10311045 if (tmp == NULL )
10321046 return NULL ;
1033- if (!PyFloat_Check (tmp )) {
1034- PyErr_SetString (PyExc_TypeError ,
1035- "float(r) didn't return a float" );
1036- Py_DECREF (tmp );
1037- return NULL ;
1038- }
1047+ assert (PyFloat_Check (tmp ));
10391048 cr .real = PyFloat_AsDouble (tmp );
10401049 cr .imag = 0.0 ;
10411050 Py_DECREF (tmp );
0 commit comments