Skip to content

Commit c38dc3c

Browse files
committed
py: Implement fallback for equality check for all types.
Return "not equal" for objects that don't implement equality check. This is as per Python specs.
1 parent ec21405 commit c38dc3c

File tree

2 files changed

+38
-11
lines changed

2 files changed

+38
-11
lines changed

py/obj.c

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -190,12 +190,19 @@ mp_int_t mp_obj_hash(mp_obj_t o_in) {
190190
}
191191
}
192192

193-
// this function implements the '==' operator (and so the inverse of '!=')
194-
// from the python language reference:
193+
// This function implements the '==' operator (and so the inverse of '!=').
194+
//
195+
// From the Python language reference:
196+
// (https://docs.python.org/3/reference/expressions.html#not-in)
195197
// "The objects need not have the same type. If both are numbers, they are converted
196198
// to a common type. Otherwise, the == and != operators always consider objects of
197199
// different types to be unequal."
198-
// note also that False==0 and True==1 are true expressions
200+
//
201+
// This means that False==0 and True==1 are true expressions.
202+
//
203+
// Furthermore, from the v3.4.2 code for object.c: "Practical amendments: If rich
204+
// comparison returns NotImplemented, == and != are decided by comparing the object
205+
// pointer."
199206
bool mp_obj_equal(mp_obj_t o1, mp_obj_t o2) {
200207
if (o1 == o2) {
201208
return true;
@@ -239,14 +246,9 @@ bool mp_obj_equal(mp_obj_t o1, mp_obj_t o2) {
239246
}
240247
}
241248

242-
if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
243-
nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
244-
"equality for given types not yet implemented"));
245-
} else {
246-
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_NotImplementedError,
247-
"equality for '%s' and '%s' types not yet implemented",
248-
mp_obj_get_type_str(o1), mp_obj_get_type_str(o2)));
249-
}
249+
// equality not implemented, and objects are not the same object, so
250+
// they are defined as not equal
251+
return false;
250252
}
251253

252254
mp_int_t mp_obj_get_int(mp_const_obj_t arg) {

tests/basics/equal_class.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# test equality for classes/instances to other types
2+
3+
class A:
4+
pass
5+
6+
class B:
7+
pass
8+
9+
class C(A):
10+
pass
11+
12+
print(A == None)
13+
print(None == A)
14+
15+
print(A == A)
16+
print(A() == A)
17+
print(A() == A())
18+
19+
print(A == B)
20+
print(A() == B)
21+
print(A() == B())
22+
23+
print(A == C)
24+
print(A() == C)
25+
print(A() == C())

0 commit comments

Comments
 (0)