1. Armin Rigo
  2. cpython-withatomic

Commits

Benjamin Peterson  committed 4bc26a8

do correct lookup of the __complex__ method

  • Participants
  • Parent commits fc833ed
  • Branches legacy-trunk

Comments (0)

Files changed (3)

File Lib/test/test_descr.py

View file
             return []
         def zero(self):
             return 0
+        def complex_num(self):
+            return 1j
         def stop(self):
             raise StopIteration
         def return_true(self, thing=None):
              set(("__bases__",)), {}),
             ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
             ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
+            ("__complex__", complex, complex_num, set(), {}),
             ]
 
         class Checker(object):

File Misc/NEWS

View file
 Core and Builtins
 -----------------
 
+- The __complex__ method is now looked up on the class of instances to make it
+  consistent with other special methods.
+
 - Issue #7462: Implement the stringlib fast search algorithm for the `rfind`,
   `rindex`, `rsplit` and `rpartition` methods.  Patch by Florent Xicluna.
 

File Objects/complexobject.c

View file
 		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();
+	if (PyInstance_Check(r)) {
+		f = PyObject_GetAttr(r, complexstr);
+		if (f == NULL) {
+			if (PyErr_ExceptionMatches(PyExc_AttributeError))
+				PyErr_Clear();
+			else
+				return NULL;
+		}
+	}
 	else {
-		PyObject *args = PyTuple_New(0);
-		if (args == NULL)
+		f = _PyObject_LookupSpecial(r, "__complex__", &complexstr);
+		if (f == NULL && PyErr_Occurred())
 			return NULL;
-		r = PyEval_CallObject(f, args);
-		Py_DECREF(args);
+	}
+	if (f != NULL) {
+		r = PyObject_CallFunctionObjArgs(f, NULL);
 		Py_DECREF(f);
 		if (r == NULL)
 			return NULL;