[Python-3000-checkins] r57364 - in python/branches/py3k: Lib/test/test_set.py Objects/setobject.c

guido.van.rossum python-3000-checkins at python.org
Fri Aug 24 01:57:24 CEST 2007


Author: guido.van.rossum
Date: Fri Aug 24 01:57:24 2007
New Revision: 57364

Modified:
   python/branches/py3k/Lib/test/test_set.py
   python/branches/py3k/Objects/setobject.c
Log:
Patch by Keir Mierle so that sets can be compared to other objects that know
how to compare themselves to sets.  (Prep work for making dict views more
set-like.)


Modified: python/branches/py3k/Lib/test/test_set.py
==============================================================================
--- python/branches/py3k/Lib/test/test_set.py	(original)
+++ python/branches/py3k/Lib/test/test_set.py	Fri Aug 24 01:57:24 2007
@@ -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):

Modified: python/branches/py3k/Objects/setobject.c
==============================================================================
--- python/branches/py3k/Objects/setobject.c	(original)
+++ python/branches/py3k/Objects/setobject.c	Fri Aug 24 01:57:24 2007
@@ -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:


More information about the Python-3000-checkins mailing list