8000 BUG: core: allow scalar type richcompare to call ndarray-subclass met… · numpy/numpy@da40eba · GitHub
[go: up one dir, main page]

Skip to content

Commit da40eba

Browse files
committed
BUG: core: allow scalar type richcompare to call ndarray-subclass methods
This makes the scalar richcmp behave exactly as "array(self) <op> other". The difference comes in when "other" is an ndarray subclass, in which case this change allows the subclass to override the comparison operations via usual Python binop dispatch rules.
1 parent afe32d7 commit da40eba

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

numpy/core/src/multiarray/scalartypes.c.src

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1082,7 +1082,11 @@ gentype_richcompare(PyObject *self, PyObject *other, int cmp_op)
10821082
if (arr == NULL) {
10831083
return NULL;
10841084
}
1085-
ret = Py_TYPE(arr)->tp_richcompare(arr, other, cmp_op);
1085+
/*
1086+
* Call via PyObject_RichCompare to ensure that other.__eq__
1087+
* has a chance to run when necessary
1088+
*/
1089+
ret = PyObject_RichCompare(arr, other, cmp_op);
10861090
Py_DECREF(arr);
10871091
return ret;
10881092
}

numpy/core/tests/test_regression.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1993,6 +1993,16 @@ def __array__(self,*args,**kwargs):
19931993
assert_(not op.eq(lhs, rhs))
19941994
assert_(op.ne(lhs, rhs))
19951995

1996+
def test_richcompare_scalar_and_subclass(self):
1997+
# gh-4709
1998+
class Foo(np.ndarray):
1999+
def __eq__(self, other):
2000+
return "OK"
2001+
x = np.array([1,2,3]).view(Foo)
2002+
assert_equal(10 == x, "OK")
2003+
assert_equal(np.int32(10) == x, "OK")
2004+
assert_equal(np.array([10]) == x, "OK")
2005+
19962006

19972007
if __name__ == "__main__":
19982008
run_module_suite()

0 commit comments

Comments
 (0)
0