summaryrefslogtreecommitdiffstats
path: root/Objects/complexobject.c
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2002-06-06 15:45:38 (GMT)
committerRaymond Hettinger <python@rcn.com>2002-06-06 15:45:38 (GMT)
commit478d47a168bf45da9014ac1a299a222726eda058 (patch)
treeb83b214c1c16891fac46710ee6ac619da3a08256 /Objects/complexobject.c
parent56f46f8d8c1af1cf150df61f5aeafa40ca0b18e5 (diff)
downloadcpython-478d47a168bf45da9014ac1a299a222726eda058.zip
cpython-478d47a168bf45da9014ac1a299a222726eda058.tar.gz
cpython-478d47a168bf45da9014ac1a299a222726eda058.tar.bz2
Close SF bug 563740. complex() now finds __complex__() in new style classes.
Made conversion failure error messages consistent between types. Added related unittests.
Diffstat (limited to 'Objects/complexobject.c')
-rw-r--r--Objects/complexobject.c49
1 files changed, 23 insertions, 26 deletions
diff --git a/Objects/complexobject.c b/Objects/complexobject.c
index adcf85a..774c546 100644
--- a/Objects/complexobject.c
+++ b/Objects/complexobject.c
@@ -811,10 +811,11 @@ complex_subtype_from_string(PyTypeObject *type, PyObject *v)
static PyObject *
complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *r, *i, *tmp;
+ PyObject *r, *i, *tmp, *f;
PyNumberMethods *nbr, *nbi = NULL;
Py_complex cr, ci;
int own_r = 0;
+ static PyObject *complexstr;
static char *kwlist[] = {"real", "imag", 0};
r = Py_False;
@@ -837,39 +838,35 @@ complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
return NULL;
}
+ /* XXX Hack to support classes with __complex__ method */
+ if (complexstr == NULL) {
+ complexstr = PyString_InternFromString("__complex__");
+ if (complexstr == NULL)
+ return NULL;
+ }
+ f = PyObject_GetAttr(r, complexstr);
+ if (f == NULL)
+ PyErr_Clear();
+ else {
+ PyObject *args = Py_BuildValue("()");
+ if (args == NULL)
+ return NULL;
+ r = PyEval_CallObject(f, args);
+ Py_DECREF(args);
+ Py_DECREF(f);
+ if (r == NULL)
+ return NULL;
+ own_r = 1;
+ }
nbr = r->ob_type->tp_as_number;
if (i != NULL)
nbi = i->ob_type->tp_as_number;
if (nbr == NULL || nbr->nb_float == NULL ||
((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
PyErr_SetString(PyExc_TypeError,
- "complex() arg can't be converted to complex");
+ "complex() argument must be a string or a number");
return NULL;
}
- /* XXX Hack to support classes with __complex__ method */
- if (PyInstance_Check(r)) {
- static PyObject *complexstr;
- PyObject *f;
- if (complexstr == NULL) {
- complexstr = PyString_InternFromString("__complex__");
- if (complexstr == NULL)
- return NULL;
- }
- f = PyObject_GetAttr(r, complexstr);
- if (f == NULL)
- PyErr_Clear();
- else {
- PyObject *args = Py_BuildValue("()");
- if (args == NULL)
- return NULL;
- r = PyEval_CallObject(f, args);
- Py_DECREF(args);
- Py_DECREF(f);
- if (r == NULL)
- return NULL;
- own_r = 1;
- }
- }
if (PyComplex_Check(r)) {
/* Note that if r is of a complex subtype, we're only
retaining its real & imag parts here, and the return