[Python-checkins] cpython: Issue #16290: __complex__ must now always return an instance of complex.

mark.dickinson python-checkins at python.org
Wed Nov 14 18:08:50 CET 2012


http://hg.python.org/cpython/rev/399e59ad0a70
changeset:   80426:399e59ad0a70
user:        Mark Dickinson <mdickinson at enthought.com>
date:        Wed Nov 14 17:08:31 2012 +0000
summary:
  Issue #16290: __complex__ must now always return an instance of complex.

files:
  Lib/test/test_complex.py |   2 ++
  Misc/NEWS                |   3 +++
  Objects/complexobject.c  |  12 ++++++------
  3 files changed, 11 insertions(+), 6 deletions(-)


diff --git a/Lib/test/test_complex.py b/Lib/test/test_complex.py
--- a/Lib/test/test_complex.py
+++ b/Lib/test/test_complex.py
@@ -221,6 +221,8 @@
         self.assertRaises(TypeError, complex, OS(None))
         self.assertRaises(TypeError, complex, NS(None))
         self.assertRaises(TypeError, complex, {})
+        self.assertRaises(TypeError, complex, NS(1.5))
+        self.assertRaises(TypeError, complex, NS(1))
 
         self.assertAlmostEqual(complex("1+10j"), 1+10j)
         self.assertAlmostEqual(complex(10), 10+0j)
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -10,6 +10,9 @@
 Core and Builtins
 -----------------
 
+- Issue #16290: A float return value from the __complex__ special method is no
+  longer accepted in the complex() constructor.
+
 - Issue #16416: On Mac OS X, operating system data are now always
   encoded/decoded to/from UTF-8/surrogateescape, instead of the locale encoding
   (which may be ASCII if no locale environment variable is set), to avoid
diff --git a/Objects/complexobject.c b/Objects/complexobject.c
--- a/Objects/complexobject.c
+++ b/Objects/complexobject.c
@@ -271,6 +271,12 @@
     if (f) {
         PyObject *res = PyObject_CallFunctionObjArgs(f, NULL);
         Py_DECREF(f);
+        if (res != NULL && !PyComplex_Check(res)) {
+            PyErr_SetString(PyExc_TypeError,
+                "__complex__ should return a complex object");
+            Py_DECREF(res);
+            return NULL;
+        }
         return res;
     }
     return NULL;
@@ -296,12 +302,6 @@
     newop = try_complex_special_method(op);
 
     if (newop) {
-        if (!PyComplex_Check(newop)) {
-            PyErr_SetString(PyExc_TypeError,
-                "__complex__ should return a complex object");
-            Py_DECREF(newop);
-            return cv;
-        }
         cv = ((PyComplexObject *)newop)->cval;
         Py_DECREF(newop);
         return cv;

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list