diff_min = 10000 # int value for which different int objects are used. class C(object): desc = ("C.__eq__() implemented with equality of x", "C.__ne__() returning NotImplemented") def __init__(self, x=None): self.x = x def __str__(self): return "C(%s)" % (self.x,) def __hash__(self): return self.x def __eq__(self, other): res = self.x == other.x print("C.__eq__(): self=%s, other=%s, returning %s" % (id(self), id(other), res)) return res def __ne__(self, other): print("C.__ne__(): self=%s, other=%s, returning NotImplemented" % (id(self), id(other))) return NotImplemented class D(object): desc = ("D.__eq__() implemented with inequality of x", "D.__ne__() returning NotImplemented") def __init__(self, x=None): self.x = x def __str__(self): return "C(%s)" % (self.x,) def __hash__(self): return self.x def __eq__(self, other): res = self.x != other.x print("D.__eq__(): self=%s, other=%s, returning %s" % (id(self), id(other), res)) return res def __ne__(self, other): print("D.__ne__(): self=%s, other=%s, returning NotImplemented" % (id(self), id(other))) return NotImplemented def test_eq(obj1, obj2, txt): print("") print(txt+":") print(" obj1: type=%s, str=%s, id=%s" % (type(obj1), str(obj1), id(obj1))) print(" obj2: type=%s, str=%s, id=%s" % (type(obj2), str(obj2), id(obj2))) print(" a) obj1 is obj2: %s" % (obj1 is obj2,)) try: res = obj1 == obj2 except Exception as exc: res = "Exception: %s" % (exc,) print(" b) obj1 == obj2: %s" % (res,)) try: res = [obj1] == [obj2] except Exception as exc: res = "Exception: %s" % (exc,) print(" c) [obj1] == [obj2]: %s" % (res,)) try: res = {obj1:'v'} == {obj2:'v'} except Exception as exc: res = "Exception: %s" % (exc,) print(" d) {obj1:'v'} == {obj2:'v'}: %s" % (res,)) try: res = {'k':obj1} == {'k':obj2} except Exception as exc: res = "Exception: %s" % (exc,) print(" e) {'k':obj1} == {'k':obj2}: %s" % (res,)) try: res = obj1 == obj2 except Exception as exc: res = "Exception: %s" % (exc,) print(" f) obj1 == obj2: %s" % (res,)) def main(): i1 = 257 i2 = (i1 + i1) // 2 assert(i1 is not i2) test_eq(i1, i2, "1. Different equal int objects") test_eq(i1, i1, "2. Same int object") f1 = 257.0 f2 = (f1 + f1) / 2 assert(f1 is not f2) test_eq(f1, f2, "3. Different equal float objects") test_eq(f1, f1, "4. Same float object") nan1 = float('nan') nan2 = float('nan') test_eq(nan1, nan2, "5. Different float NaN objects") test_eq(nan1, nan1, "6. Same float NaN object") c1 = C(256) c2 = C(256) test_eq(c1, c2, "7. Different objects (with equal x) of class C\n (%s)" % (",\n ".join(C.desc),)) test_eq(c1, c1, "8. Same object of class C\n (%s)" % (",\n ".join(C.desc),)) d1 = D(256) d2 = D(256) test_eq(d1, d2, "9. Different objects (with equal x) of class D\n (%s)" % (",\n ".join(D.desc),)) test_eq(d1, d1, "10. Same object of class D\n (%s)" % (",\n ".join(D.desc),)) if __name__ == '__main__': main()