Skip to content

Commit ecdae19

Browse files
committed
do correct lookup of the __complex__ method
1 parent 37559a0 commit ecdae19

3 files changed

Lines changed: 20 additions & 8 deletions

File tree

‎Lib/test/test_descr.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1691,6 +1691,8 @@ def empty_seq(self):
16911691
return []
16921692
def zero(self):
16931693
return 0
1694+
def complex_num(self):
1695+
return 1j
16941696
def stop(self):
16951697
raise StopIteration
16961698
def return_true(self, thing=None):
@@ -1725,6 +1727,7 @@ def some_number(self_, key):
17251727
set(("__bases__",)), {}),
17261728
("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
17271729
("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
1730+
("__complex__", complex, complex_num, set(), {}),
17281731
]
17291732

17301733
class Checker(object):

‎Misc/NEWS‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ What's New in Python 2.7 alpha 2?
1212
Core and Builtins
1313
-----------------
1414

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

‎Objects/complexobject.c‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1114,21 +1114,27 @@ complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
11141114
return NULL;
11151115
}
11161116

1117-
/* XXX Hack to support classes with __complex__ method */
11181117
if (complexstr == NULL) {
11191118
complexstr = PyString_InternFromString("__complex__");
11201119
if (complexstr == NULL)
11211120
return NULL;
11221121
}
1123-
f = PyObject_GetAttr(r, complexstr);
1124-
if (f == NULL)
1125-
PyErr_Clear();
1122+
if (PyInstance_Check(r)) {
1123+
f = PyObject_GetAttr(r, complexstr);
1124+
if (f == NULL) {
1125+
if (PyErr_ExceptionMatches(PyExc_AttributeError))
1126+
PyErr_Clear();
1127+
else
1128+
return NULL;
1129+
}
1130+
}
11261131
else {
1127-
PyObject *args = PyTuple_New(0);
1128-
if (args == NULL)
1132+
f = _PyObject_LookupSpecial(r, "__complex__", &complexstr);
1133+
if (f == NULL && PyErr_Occurred())
11291134
return NULL;
1130-
r = PyEval_CallObject(f, args);
1131-
Py_DECREF(args);
1135+
}
1136+
if (f != NULL) {
1137+
r = PyObject_CallFunctionObjArgs(f, NULL);
11321138
Py_DECREF(f);
11331139
if (r == NULL)
11341140
return NULL;

0 commit comments

Comments
 (0)