]> granicus.if.org Git - python/commitdiff
By default, != returns the opposite of ==, unless the latter returns
authorGuido van Rossum <guido@python.org>
Tue, 27 Mar 2007 22:37:34 +0000 (22:37 +0000)
committerGuido van Rossum <guido@python.org>
Tue, 27 Mar 2007 22:37:34 +0000 (22:37 +0000)
NotImplemented.

(Is this worth backporting to 2.6?  It seems so useful...!)

Lib/test/test_compare.py
Misc/NEWS
Objects/typeobject.c

index 1d0da692097ba7a31d4f46615b4f17a759bcfc3b..c6608379a13dbca0fe256cbd467a236eaa96ceab 100644 (file)
@@ -39,6 +39,12 @@ class ComparisonTest(unittest.TestCase):
                 self.assertEqual(a == b, id(a) == id(b),
                                  'a=%r, b=%r' % (a, b))
 
+    def test_ne_defaults_to_not_eq(self):
+        a = Cmp(1)
+        b = Cmp(1)
+        self.assertTrue(a == b)
+        self.assertFalse(a != b)
+
 def test_main():
     test_support.run_unittest(ComparisonTest)
 
index c2699ec53aeeb61f0919ddc20e5442ec24b8f26a..4f647d2be5e670c4c242b15b32a75fa480d9bbc3 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -28,6 +28,9 @@ TO DO
 Core and Builtins
 -----------------
 
+- By default, != returns the opposite of ==, unless the latter returns
+  NotImplemented.
+
 - Patch #1680961: sys.exitfunc has been removed and replaced with a private
   C-level API.
 
index e626a17f76ca4f9a544e41b51c37122f20913871..be6f279466f85e6c4e281b6f2fc5fde9fe896c69 100644 (file)
@@ -2314,7 +2314,22 @@ object_richcompare(PyObject *self, PyObject *other, int op)
                break;
 
        case Py_NE:
-               res = (self != other) ? Py_True : Py_False;
+               /* By default, != returns the opposite of ==,
+                  unless the latter returns NotImplemented. */
+               res = PyObject_RichCompare(self, other, Py_EQ);
+               if (res != NULL && res != Py_NotImplemented) {
+                       int ok = PyObject_IsTrue(res);
+                       Py_DECREF(res);
+                       if (ok < 0)
+                               res = NULL;
+                       else {
+                               if (ok)
+                                       res = Py_False;
+                               else
+                                       res = Py_True;
+                               Py_INCREF(res);
+                       }
+               }
                break;
 
        default: