Skip to content

Commit d20fb82

Browse files
committed
Issue #16290: __complex__ must now always return an instance of complex.
1 parent 2eb2f5e commit d20fb82

3 files changed

Lines changed: 11 additions & 6 deletions

File tree

Lib/test/test_complex.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,8 @@ def __complex__(self): return self.value
221221
self.assertRaises(TypeError, complex, OS(None))
222222
self.assertRaises(TypeError, complex, NS(None))
223223
self.assertRaises(TypeError, complex, {})
224+
self.assertRaises(TypeError, complex, NS(1.5))
225+
self.assertRaises(TypeError, complex, NS(1))
224226

225227
self.assertAlmostEqual(complex("1+10j"), 1+10j)
226228
self.assertAlmostEqual(complex(10), 10+0j)

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ What's New in Python 3.4.0 Alpha 1?
1010
Core and Builtins
1111
-----------------
1212

13+
- Issue #16290: A float return value from the __complex__ special method is no
14+
longer accepted in the complex() constructor.
15+
1316
- Issue #16416: On Mac OS X, operating system data are now always
1417
encoded/decoded to/from UTF-8/surrogateescape, instead of the locale encoding
1518
(which may be ASCII if no locale environment variable is set), to avoid

Objects/complexobject.c

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,12 @@ try_complex_special_method(PyObject *op) {
271271
if (f) {
272272
PyObject *res = PyObject_CallFunctionObjArgs(f, NULL);
273273
Py_DECREF(f);
274+
if (res != NULL && !PyComplex_Check(res)) {
275+
PyErr_SetString(PyExc_TypeError,
276+
"__complex__ should return a complex object");
277+
Py_DECREF(res);
278+
return NULL;
279+
}
274280
return res;
275281
}
276282
return NULL;
@@ -296,12 +302,6 @@ PyComplex_AsCComplex(PyObject *op)
296302
newop = try_complex_special_method(op);
297303

298304
if (newop) {
299-
if (!PyComplex_Check(newop)) {
300-
PyErr_SetString(PyExc_TypeError,
301-
"__complex__ should return a complex object");
302-
Py_DECREF(newop);
303-
return cv;
304-
}
305305
cv = ((PyComplexObject *)newop)->cval;
306306
Py_DECREF(newop);
307307
return cv;

0 commit comments

Comments
 (0)