This patch fixes rich set comparison so that x < y works when x is a
set and y is something which implements the corresponding comparison.

Keir
Index: Objects/setobject.c
===================================================================
--- Objects/setobject.c	(revision 57362)
+++ Objects/setobject.c	(working copy)
@@ -1607,12 +1607,8 @@
 	PyObject *r1, *r2;
 
 	if(!PyAnySet_Check(w)) {
-		if (op == Py_EQ)
-			Py_RETURN_FALSE;
-		if (op == Py_NE)
-			Py_RETURN_TRUE;
-		PyErr_SetString(PyExc_TypeError, "can only compare to a set");
-		return NULL;
+		Py_INCREF(Py_NotImplemented);
+		return Py_NotImplemented;
 	}
 	switch (op) {
 	case Py_EQ:
Index: Lib/test/test_set.py
===================================================================
--- Lib/test/test_set.py	(revision 57362)
+++ Lib/test/test_set.py	(working copy)
@@ -492,6 +492,42 @@
         s = None
         self.assertRaises(ReferenceError, str, p)
 
+    def test_rich_compare(self):
+        class TestRichSetCompare:
+            def __gt__(self, some_set):
+                self.gt_called = True
+                return False
+            def __lt__(self, some_set):
+                self.lt_called = True
+                return False
+            def __ge__(self, some_set):
+                self.ge_called = True
+                return False
+            def __le__(self, some_set):
+                self.le_called = True
+                return False
+
+        # This first tries the bulitin rich set comparison, which doesn't know
+        # how to handle the custom object. Upon returning NotImplemented, the
+        # corresponding comparison on the right object is invoked.
+        myset = {1, 2, 3}
+
+        myobj = TestRichSetCompare()
+        myset < myobj
+        self.assert_(myobj.gt_called)
+
+        myobj = TestRichSetCompare()
+        myset > myobj
+        self.assert_(myobj.lt_called)
+
+        myobj = TestRichSetCompare()
+        myset <= myobj
+        self.assert_(myobj.ge_called)
+
+        myobj = TestRichSetCompare()
+        myset >= myobj
+        self.assert_(myobj.le_called)
+
     # C API test only available in a debug build
     if hasattr(set, "test_c_api"):
         def test_c_api(self):
_______________________________________________
Python-3000 mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-3000
Unsubscribe: 
http://mail.python.org/mailman/options/python-3000/archive%40mail-archive.com

Reply via email to