summaryrefslogtreecommitdiffstatshomepage
diff options
context:
space:
mode:
authorDamien George <damien.p.george@gmail.com>2015-01-11 15:13:18 +0000
committerDamien George <damien.p.george@gmail.com>2015-01-11 15:13:18 +0000
commitc38dc3ccc76d1a9bf867704f43ea5d15da3fea7b (patch)
tree637c47bf5d538b67c61a7c1f21719c18f0d4cd5a
parentec21405821dd997d337a0f387db9b1a45b32834b (diff)
downloadmicropython-c38dc3ccc76d1a9bf867704f43ea5d15da3fea7b.tar.gz
micropython-c38dc3ccc76d1a9bf867704f43ea5d15da3fea7b.zip
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.
-rw-r--r--py/obj.c24
-rw-r--r--tests/basics/equal_class.py25
2 files changed, 38 insertions, 11 deletions
diff --git a/py/obj.c b/py/obj.c
index 0caf100745..e58330a9d5 100644
--- a/py/obj.c
+++ b/py/obj.c
@@ -190,12 +190,19 @@ mp_int_t mp_obj_hash(mp_obj_t o_in) {
}
}
-// this function implements the '==' operator (and so the inverse of '!=')
-// from the python language reference:
+// This function implements the '==' operator (and so the inverse of '!=').
+//
+// From the Python language reference:
+// (https://docs.python.org/3/reference/expressions.html#not-in)
// "The objects need not have the same type. If both are numbers, they are converted
// to a common type. Otherwise, the == and != operators always consider objects of
// different types to be unequal."
-// note also that False==0 and True==1 are true expressions
+//
+// This means that False==0 and True==1 are true expressions.
+//
+// Furthermore, from the v3.4.2 code for object.c: "Practical amendments: If rich
+// comparison returns NotImplemented, == and != are decided by comparing the object
+// pointer."
bool mp_obj_equal(mp_obj_t o1, mp_obj_t o2) {
if (o1 == o2) {
return true;
@@ -239,14 +246,9 @@ bool mp_obj_equal(mp_obj_t o1, mp_obj_t o2) {
}
}
- if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
- nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
- "equality for given types not yet implemented"));
- } else {
- nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_NotImplementedError,
- "equality for '%s' and '%s' types not yet implemented",
- mp_obj_get_type_str(o1), mp_obj_get_type_str(o2)));
- }
+ // equality not implemented, and objects are not the same object, so
+ // they are defined as not equal
+ return false;
}
mp_int_t mp_obj_get_int(mp_const_obj_t arg) {
diff --git a/tests/basics/equal_class.py b/tests/basics/equal_class.py
new file mode 100644
index 0000000000..3806f7cba1
--- /dev/null
+++ b/tests/basics/equal_class.py
@@ -0,0 +1,25 @@
+# test equality for classes/instances to other types
+
+class A:
+ pass
+
+class B:
+ pass
+
+class C(A):
+ pass
+
+print(A == None)
+print(None == A)
+
+print(A == A)
+print(A() == A)
+print(A() == A())
+
+print(A == B)
+print(A() == B)
+print(A() == B())
+
+print(A == C)
+print(A() == C)
+print(A() == C())