From: Raymond Hettinger Date: Thu, 29 Aug 2002 14:22:51 +0000 (+0000) Subject: complex() was the only numeric constructor that created a new instance X-Git-Tag: v2.3c1~4265 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=604cd6ae79e0e7ff52b96bba9aa9fbd6c21e1e8f;p=python complex() was the only numeric constructor that created a new instance when given its own type as an argument. --- diff --git a/Lib/test/test_b1.py b/Lib/test/test_b1.py index d80767b0cc..5536246e25 100644 --- a/Lib/test/test_b1.py +++ b/Lib/test/test_b1.py @@ -140,6 +140,10 @@ if complex(0.0, 3.14) != 3.14j: raise TestFailed, 'complex(0.0, 3.14)' if complex("1") != 1+0j: raise TestFailed, 'complex("1")' if complex("1j") != 1j: raise TestFailed, 'complex("1j")' +c = 3.14 + 1j +if complex(c) is not c: raise TestFailed, 'complex(3.14+1j) changed identity' +del c + try: complex("1", "1") except TypeError: pass else: raise TestFailed, 'complex("1", "1")' diff --git a/Objects/complexobject.c b/Objects/complexobject.c index bb2835420a..56638d5ec0 100644 --- a/Objects/complexobject.c +++ b/Objects/complexobject.c @@ -823,6 +823,15 @@ complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds) if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist, &r, &i)) return NULL; + + /* Special-case for single argumet that is already complex */ + if (PyComplex_CheckExact(r) && i == NULL) { + /* Note that we can't know whether it's safe to return + a complex *subclass* instance as-is, hence the restriction + to exact complexes here. */ + Py_INCREF(r); + return r; + } if (PyString_Check(r) || PyUnicode_Check(r)) { if (i != NULL) { PyErr_SetString(PyExc_TypeError,