bpo-29894: Deprecate returning an instance of complex subclass from __complex__. (#798)

In a future versions of Python this can be an error.
This commit is contained in:
Serhiy Storchaka 2017-03-24 21:28:43 +02:00 committed by GitHub
parent af7b9ec5c8
commit 671079ef60
4 changed files with 28 additions and 13 deletions

View file

@ -274,7 +274,8 @@ PyComplex_ImagAsDouble(PyObject *op)
}
static PyObject *
try_complex_special_method(PyObject *op) {
try_complex_special_method(PyObject *op)
{
PyObject *f;
_Py_IDENTIFIER(__complex__);
@ -282,9 +283,22 @@ try_complex_special_method(PyObject *op) {
if (f) {
PyObject *res = _PyObject_CallNoArg(f);
Py_DECREF(f);
if (res != NULL && !PyComplex_Check(res)) {
PyErr_SetString(PyExc_TypeError,
"__complex__ should return a complex object");
if (!res || PyComplex_CheckExact(res)) {
return res;
}
if (!PyComplex_Check(res)) {
PyErr_Format(PyExc_TypeError,
"__complex__ returned non-complex (type %.200s)",
res->ob_type->tp_name);
Py_DECREF(res);
return NULL;
}
/* Issue #29894: warn if 'res' not of exact type complex. */
if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
"__complex__ returned non-complex (type %.200s). "
"The ability to return an instance of a strict subclass of complex "
"is deprecated, and may be removed in a future version of Python.",
res->ob_type->tp_name)) {
Py_DECREF(res);
return NULL;
}
@ -1030,12 +1044,7 @@ complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i)
}
if (tmp == NULL)
return NULL;
if (!PyFloat_Check(tmp)) {
PyErr_SetString(PyExc_TypeError,
"float(r) didn't return a float");
Py_DECREF(tmp);
return NULL;
}
assert(PyFloat_Check(tmp));
cr.real = PyFloat_AsDouble(tmp);
cr.imag = 0.0;
Py_DECREF(tmp);