Skip to content
This repository was archived by the owner on Jan 30, 2023. It is now read-only.

Commit e311ab1

Browse files
jdemeyermezzarobba
authored andcommitted
Element richcmp: never use id()
1 parent a6ceab9 commit e311ab1

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

src/sage/structure/coerce.pyx

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,8 @@ see the documentation for :class:`Parent`.
7676
from __future__ import print_function, absolute_import
7777

7878
from cpython.object cimport (PyObject, PyTypeObject,
79-
PyObject_CallObject, PyObject_RichCompare, Py_TYPE)
79+
PyObject_CallObject, PyObject_RichCompare, Py_TYPE,
80+
Py_EQ, Py_NE, Py_LT, Py_LE, Py_GT, Py_GE)
8081
from cpython.weakref cimport PyWeakref_GET_OBJECT, PyWeakref_NewRef
8182
from libc.string cimport strncmp
8283

@@ -1893,14 +1894,17 @@ cdef class CoercionModel:
18931894
sage: richcmp(int(1), float(2), op_GE)
18941895
False
18951896
1896-
If there is no coercion, only comparisons for equality make
1897-
sense::
1897+
If there is no coercion, we only support ``==`` and ``!=``::
18981898
18991899
sage: x = QQ.one(); y = GF(2).one()
19001900
sage: richcmp(x, y, op_EQ)
19011901
False
19021902
sage: richcmp(x, y, op_NE)
19031903
True
1904+
sage: richcmp(x, y, op_GT)
1905+
Traceback (most recent call last):
1906+
...
1907+
TypeError: unsupported operand parent(s) for >: 'Rational Field' and 'Finite Field of size 2'
19041908
19051909
We support non-Sage types with the usual Python convention::
19061910
@@ -1950,13 +1954,23 @@ cdef class CoercionModel:
19501954
if res is not NotImplemented:
19511955
return res
19521956

1953-
# Final attempt: compare by id()
1954-
if (<unsigned long><PyObject*>x) >= (<unsigned long><PyObject*>y):
1955-
# It cannot happen that x is y, since they don't
1956-
# have the same parent.
1957-
return rich_to_bool(op, 1)
1957+
# At this point, we have 2 objects which cannot be coerced to
1958+
# a common parent. So we assume that they are not equal.
1959+
if op == Py_EQ:
1960+
return False
1961+
if op == Py_NE:
1962+
return True
1963+
1964+
# It does not make sense to compare x and y with an inequality,
1965+
# so we raise an exception.
1966+
if op == Py_LT:
1967+
raise bin_op_exception('<', x, y)
1968+
elif op == Py_LE:
1969+
raise bin_op_exception('<=', x, y)
1970+
elif op == Py_GT:
1971+
raise bin_op_exception('>', x, y)
19581972
else:
1959-
return rich_to_bool(op, -1)
1973+
raise bin_op_exception('>=', x, y)
19601974

19611975
def _coercion_error(self, x, x_map, x_elt, y, y_map, y_elt):
19621976
"""

0 commit comments

Comments
 (0)