summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorGuido van Rossum <guido@python.org>2006-08-24 00:41:19 (GMT)
committerGuido van Rossum <guido@python.org>2006-08-24 00:41:19 (GMT)
commit47b9ff6ba11fab4c90556357c437cb4feec1e853 (patch)
treeb5319f74e08caf3276275462b14372b4da9f7dee /Lib
parent9a6e62b947ebb5547ca9a164f6145a461b98d86a (diff)
downloadcpython-47b9ff6ba11fab4c90556357c437cb4feec1e853.zip
cpython-47b9ff6ba11fab4c90556357c437cb4feec1e853.tar.gz
cpython-47b9ff6ba11fab4c90556357c437cb4feec1e853.tar.bz2
Restructure comparison dramatically. There is no longer a default
*ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
Diffstat (limited to 'Lib')
-rw-r--r--Lib/StringIO.py4
-rw-r--r--Lib/UserDict.py21
-rwxr-xr-xLib/UserString.py32
-rw-r--r--Lib/ctypes/test/test_simplesubclasses.py6
-rw-r--r--Lib/decimal.py21
-rw-r--r--Lib/distutils/version.py39
-rw-r--r--Lib/doctest.py9
-rw-r--r--Lib/optparse.py8
-rw-r--r--Lib/plat-mac/plistlib.py8
-rw-r--r--Lib/pprint.py7
-rw-r--r--Lib/sqlite3/test/types.py6
-rw-r--r--Lib/test/mapping_tests.py25
-rw-r--r--Lib/test/output/test_class20
-rw-r--r--Lib/test/pickletester.py4
-rw-r--r--Lib/test/test_bisect.py7
-rw-r--r--Lib/test/test_buffer.py44
-rw-r--r--Lib/test/test_builtin.py20
-rw-r--r--Lib/test/test_calendar.py2
-rw-r--r--Lib/test/test_cgi.py18
-rw-r--r--Lib/test/test_class.py24
-rw-r--r--Lib/test/test_compare.py6
-rw-r--r--Lib/test/test_copy.py70
-rw-r--r--Lib/test/test_decimal.py4
-rw-r--r--Lib/test/test_descr.py83
-rw-r--r--Lib/test/test_descrtut.py5
-rw-r--r--Lib/test/test_dict.py11
-rw-r--r--Lib/test/test_grammar.py4
-rw-r--r--Lib/test/test_heapq.py3
-rw-r--r--Lib/test/test_itertools.py6
-rw-r--r--Lib/test/test_mutants.py9
-rw-r--r--Lib/test/test_operations.py4
-rw-r--r--Lib/test/test_set.py23
-rw-r--r--Lib/test/test_sets.py15
-rw-r--r--Lib/test/test_slice.py6
-rw-r--r--Lib/test/test_sort.py6
-rw-r--r--Lib/test/test_support.py4
-rw-r--r--Lib/test/test_types.py1
-rw-r--r--Lib/test/test_userdict.py2
-rw-r--r--Lib/test/test_weakref.py6
-rw-r--r--Lib/uuid.py33
-rw-r--r--Lib/xmlrpclib.py71
41 files changed, 452 insertions, 245 deletions
diff --git a/Lib/StringIO.py b/Lib/StringIO.py
index 1e5f254..7d57d80 100644
--- a/Lib/StringIO.py
+++ b/Lib/StringIO.py
@@ -116,7 +116,7 @@ class StringIO:
_complain_ifclosed(self.closed)
return self.pos
- def read(self, n = -1):
+ def read(self, n=None):
"""Read at most size bytes from the file
(less if the read hits EOF before obtaining size bytes).
@@ -128,6 +128,8 @@ class StringIO:
if self.buflist:
self.buf += ''.join(self.buflist)
self.buflist = []
+ if n is None:
+ n = -1
if n < 0:
newpos = self.len
else:
diff --git a/Lib/UserDict.py b/Lib/UserDict.py
index b560a11..1190221 100644
--- a/Lib/UserDict.py
+++ b/Lib/UserDict.py
@@ -8,11 +8,16 @@ class UserDict:
if len(kwargs):
self.update(kwargs)
def __repr__(self): return repr(self.data)
- def __cmp__(self, dict):
+ def __eq__(self, dict):
if isinstance(dict, UserDict):
- return cmp(self.data, dict.data)
+ return self.data == dict.data
else:
- return cmp(self.data, dict)
+ return self.data == dict
+ def __ne__(self, dict):
+ if isinstance(dict, UserDict):
+ return self.data != dict.data
+ else:
+ return self.data != dict
def __len__(self): return len(self.data)
def __getitem__(self, key):
if key in self.data:
@@ -162,11 +167,13 @@ class DictMixin:
return default
def __repr__(self):
return repr(dict(self.iteritems()))
- def __cmp__(self, other):
- if other is None:
- return 1
+ def __eq__(self, other):
+ if isinstance(other, DictMixin):
+ other = dict(other.iteritems())
+ return dict(self.iteritems()) == other
+ def __ne__(self, other):
if isinstance(other, DictMixin):
other = dict(other.iteritems())
- return cmp(dict(self.iteritems()), other)
+ return dict(self.iteritems()) != other
def __len__(self):
return len(self.keys())
diff --git a/Lib/UserString.py b/Lib/UserString.py
index 60dc34b..271026c 100755
--- a/Lib/UserString.py
+++ b/Lib/UserString.py
@@ -25,11 +25,37 @@ class UserString:
def __complex__(self): return complex(self.data)
def __hash__(self): return hash(self.data)
- def __cmp__(self, string):
+ def __eq__(self, string):
if isinstance(string, UserString):
- return cmp(self.data, string.data)
+ return self.data == string.data
else:
- return cmp(self.data, string)
+ return self.data == string
+ def __ne__(self, string):
+ if isinstance(string, UserString):
+ return self.data != string.data
+ else:
+ return self.data != string
+ def __lt__(self, string):
+ if isinstance(string, UserString):
+ return self.data < string.data
+ else:
+ return self.data < string
+ def __le__(self, string):
+ if isinstance(string, UserString):
+ return self.data <= string.data
+ else:
+ return self.data <= string
+ def __gt__(self, string):
+ if isinstance(string, UserString):
+ return self.data > string.data
+ else:
+ return self.data > string
+ def __ge__(self, string):
+ if isinstance(string, UserString):
+ return self.data >= string.data
+ else:
+ return self.data >= string
+
def __contains__(self, char):
return char in self.data
diff --git a/Lib/ctypes/test/test_simplesubclasses.py b/Lib/ctypes/test/test_simplesubclasses.py
index 7155170..420c0a0 100644
--- a/Lib/ctypes/test/test_simplesubclasses.py
+++ b/Lib/ctypes/test/test_simplesubclasses.py
@@ -2,10 +2,10 @@ import unittest
from ctypes import *
class MyInt(c_int):
- def __cmp__(self, other):
+ def __eq__(self, other):
if type(other) != MyInt:
- return -1
- return cmp(self.value, other.value)
+ return NotImplementedError
+ return self.value == other.value
class Test(unittest.TestCase):
diff --git a/Lib/decimal.py b/Lib/decimal.py
index 210db52..a8fde82 100644
--- a/Lib/decimal.py
+++ b/Lib/decimal.py
@@ -706,6 +706,26 @@ class Decimal(object):
return NotImplemented
return self.__cmp__(other) != 0
+ def __lt__(self, other):
+ if not isinstance(other, (Decimal, int, long)):
+ return NotImplemented
+ return self.__cmp__(other) < 0
+
+ def __le__(self, other):
+ if not isinstance(other, (Decimal, int, long)):
+ return NotImplemented
+ return self.__cmp__(other) <= 0
+
+ def __gt__(self, other):
+ if not isinstance(other, (Decimal, int, long)):
+ return NotImplemented
+ return self.__cmp__(other) > 0
+
+ def __ge__(self, other):
+ if not isinstance(other, (Decimal, int, long)):
+ return NotImplemented
+ return self.__cmp__(other) >= 0
+
def compare(self, other, context=None):
"""Compares one to another.
@@ -1894,6 +1914,7 @@ class Decimal(object):
ans = self._check_nans(context=context)
if ans:
return ans
+ return self
if self._exp >= 0:
return self
if context is None:
diff --git a/Lib/distutils/version.py b/Lib/distutils/version.py
index 71a5614..2cd3636 100644
--- a/Lib/distutils/version.py
+++ b/Lib/distutils/version.py
@@ -32,7 +32,8 @@ from types import StringType
class Version:
"""Abstract base class for version numbering classes. Just provides
constructor (__init__) and reproducer (__repr__), because those
- seem to be the same for all version numbering classes.
+ seem to be the same for all version numbering classes; and route
+ rich comparisons to __cmp__.
"""
def __init__ (self, vstring=None):
@@ -42,6 +43,42 @@ class Version:
def __repr__ (self):
return "%s ('%s')" % (self.__class__.__name__, str(self))
+ def __eq__(self, other):
+ c = self.__cmp__(other)
+ if c is NotImplemented:
+ return c
+ return c == 0
+
+ def __ne__(self, other):
+ c = self.__cmp__(other)
+ if c is NotImplemented:
+ return c
+ return c != 0
+
+ def __lt__(self, other):
+ c = self.__cmp__(other)
+ if c is NotImplemented:
+ return c
+ return c < 0
+
+ def __le__(self, other):
+ c = self.__cmp__(other)
+ if c is NotImplemented:
+ return c
+ return c <= 0
+
+ def __gt__(self, other):
+ c = self.__cmp__(other)
+ if c is NotImplemented:
+ return c
+ return c > 0
+
+ def __ge__(self, other):
+ c = self.__cmp__(other)
+ if c is NotImplemented:
+ return c
+ return c >= 0
+
# Interface for version-number classes -- must be implemented
# by the following classes (the concrete ones -- Version should
diff --git a/Lib/doctest.py b/Lib/doctest.py
index fe734b3..2774ec1 100644
--- a/Lib/doctest.py
+++ b/Lib/doctest.py
@@ -469,11 +469,12 @@ class DocTest:
# This lets us sort tests by name:
- def __cmp__(self, other):
+ def __lt__(self, other):
if not isinstance(other, DocTest):
- return -1
- return cmp((self.name, self.filename, self.lineno, id(self)),
- (other.name, other.filename, other.lineno, id(other)))
+ return NotImplemented
+ return ((self.name, self.filename, self.lineno, id(self))
+ <
+ (other.name, other.filename, other.lineno, id(other)))
######################################################################
## 3. DocTestParser
diff --git a/Lib/optparse.py b/Lib/optparse.py
index 0972f74..f8f643d 100644
--- a/Lib/optparse.py
+++ b/Lib/optparse.py
@@ -838,13 +838,13 @@ class Values:
__repr__ = _repr
- def __cmp__(self, other):
+ def __eq__(self, other):
if isinstance(other, Values):
- return cmp(self.__dict__, other.__dict__)
+ return self.__dict__ == other.__dict__
elif isinstance(other, types.DictType):
- return cmp(self.__dict__, other)
+ return self.__dict__ == other
else:
- return -1
+ return NotImplemented
def _update_careful(self, dict):
"""
diff --git a/Lib/plat-mac/plistlib.py b/Lib/plat-mac/plistlib.py
index 49bd556..f91f1d3 100644
--- a/Lib/plat-mac/plistlib.py
+++ b/Lib/plat-mac/plistlib.py
@@ -374,13 +374,13 @@ class Data:
def asBase64(self, maxlinelength=76):
return _encodeBase64(self.data, maxlinelength)
- def __cmp__(self, other):
+ def __eq__(self, other):
if isinstance(other, self.__class__):
- return cmp(self.data, other.data)
+ return self.data == other.data
elif isinstance(other, str):
- return cmp(self.data, other)
+ return self.data == other
else:
- return cmp(id(self), id(other))
+ return id(self) == id(other)
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, repr(self.data))
diff --git a/Lib/pprint.py b/Lib/pprint.py
index 19a3dc2..97135eb 100644
--- a/Lib/pprint.py
+++ b/Lib/pprint.py
@@ -246,7 +246,12 @@ def _safe_repr(object, context, maxlevels, level):
append = components.append
level += 1
saferepr = _safe_repr
- for k, v in sorted(object.items()):
+ items = object.items()
+ try:
+ items = sorted(items)
+ except TypeError:
+ items = sorted(items, key=lambda (k, v): (str(type(k)), k, v))
+ for k, v in items:
krepr, kreadable, krecur = saferepr(k, context, maxlevels, level)
vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level)
append("%s: %s" % (krepr, vrepr))
diff --git a/Lib/sqlite3/test/types.py b/Lib/sqlite3/test/types.py
index 8da5722..9a11f5c 100644
--- a/Lib/sqlite3/test/types.py
+++ b/Lib/sqlite3/test/types.py
@@ -86,6 +86,12 @@ class DeclTypesTests(unittest.TestCase):
else:
return 1
+ def __eq__(self, other):
+ c = self.__cmp__(other)
+ if c is NotImplemented:
+ return c
+ return c == 0
+
def __conform__(self, protocol):
if protocol is sqlite.PrepareProtocol:
return self.val
diff --git a/Lib/test/mapping_tests.py b/Lib/test/mapping_tests.py
index b917540..15f9add 100644
--- a/Lib/test/mapping_tests.py
+++ b/Lib/test/mapping_tests.py
@@ -60,10 +60,10 @@ class BasicTestMappingProtocol(unittest.TestCase):
for k in self.other:
self.failIf(k in d)
#cmp
- self.assertEqual(cmp(p,p), 0)
- self.assertEqual(cmp(d,d), 0)
- self.assertEqual(cmp(p,d), -1)
- self.assertEqual(cmp(d,p), 1)
+ self.assertEqual(p, p)
+ self.assertEqual(d, d)
+ self.assertNotEqual(p, d)
+ self.assertNotEqual(d, p)
#__non__zero__
if p: self.fail("Empty mapping must compare to False")
if not d: self.fail("Full mapping must compare to True")
@@ -623,9 +623,10 @@ class TestHashMappingProtocol(TestMappingProtocol):
d = self._full_mapping({1: BadRepr()})
self.assertRaises(Exc, repr, d)
- def test_le(self):
- self.assert_(not (self._empty_mapping() < self._empty_mapping()))
- self.assert_(not (self._full_mapping({1: 2}) < self._full_mapping({1L: 2L})))
+ def test_eq(self):
+ self.assertEqual(self._empty_mapping(), self._empty_mapping())
+ self.assertEqual(self._full_mapping({1: 2}),
+ self._full_mapping({1L: 2L}))
class Exc(Exception): pass
@@ -633,16 +634,12 @@ class TestHashMappingProtocol(TestMappingProtocol):
def __eq__(self, other):
raise Exc()
def __hash__(self):
- return 42
+ return 1
d1 = self._full_mapping({BadCmp(): 1})
d2 = self._full_mapping({1: 1})
- try:
- d1 < d2
- except Exc:
- pass
- else:
- self.fail("< didn't raise Exc")
+ self.assertRaises(Exc, lambda: BadCmp()==1)
+ self.assertRaises(Exc, lambda: d1==d2)
def test_setdefault(self):
TestMappingProtocol.test_setdefault(self)
diff --git a/Lib/test/output/test_class b/Lib/test/output/test_class
index 14d43a8..7d8ab5e 100644
--- a/Lib/test/output/test_class
+++ b/Lib/test/output/test_class
@@ -51,16 +51,16 @@ __hex__: ()
__hash__: ()
__repr__: ()
__str__: ()
-__cmp__: (1,)
-__cmp__: (1,)
-__cmp__: (1,)
-__cmp__: (1,)
-__cmp__: (1,)
-__cmp__: (1,)
-__cmp__: (1,)
-__cmp__: (1,)
-__cmp__: (1,)
-__cmp__: (1,)
+__eq__: (1,)
+__lt__: (1,)
+__gt__: (1,)
+__ne__: (1,)
+__ne__: (1,)
+__eq__: (1,)
+__gt__: (1,)
+__lt__: (1,)
+__ne__: (1,)
+__ne__: (1,)
__del__: ()
__getattr__: ('spam',)
__setattr__: ('eggs', 'spam, spam, spam and ham')
diff --git a/Lib/test/pickletester.py b/Lib/test/pickletester.py
index 42853c4..30c1e7c 100644
--- a/Lib/test/pickletester.py
+++ b/Lib/test/pickletester.py
@@ -65,8 +65,8 @@ class ExtensionSaver:
copy_reg.add_extension(pair[0], pair[1], code)
class C:
- def __cmp__(self, other):
- return cmp(self.__dict__, other.__dict__)
+ def __eq__(self, other):
+ return self.__dict__ == other.__dict__
import __main__
__main__.C = C
diff --git a/Lib/test/test_bisect.py b/Lib/test/test_bisect.py
index 302ff63..772e808 100644
--- a/Lib/test/test_bisect.py
+++ b/Lib/test/test_bisect.py
@@ -174,8 +174,13 @@ class GetOnly:
class CmpErr:
"Dummy element that always raises an error during comparison"
- def __cmp__(self, other):
+ def __lt__(self, other):
raise ZeroDivisionError
+ __gt__ = __lt__
+ __le__ = __lt__
+ __ge__ = __lt__
+ __eq__ = __lt__
+ __ne__ = __lt__
class TestErrorHandling(unittest.TestCase):
diff --git a/Lib/test/test_buffer.py b/Lib/test/test_buffer.py
new file mode 100644
index 0000000..eb6e9ea
--- /dev/null
+++ b/Lib/test/test_buffer.py
@@ -0,0 +1,44 @@
+"""Unit tests for buffer objects.
+
+For now, we just test (the brand new) rich comparison.
+
+"""
+
+import unittest
+from test import test_support
+
+class BufferTests(unittest.TestCase):
+
+ def test_comparison(self):
+ a = buffer("a.b.c")
+ b = buffer("a.b" + ".c")
+ self.assert_(a == b)
+ self.assert_(a <= b)
+ self.assert_(a >= b)
+ self.assert_(a == "a.b.c")
+ self.assert_(a <= "a.b.c")
+ self.assert_(a >= "a.b.c")
+ b = buffer("a.b.c.d")
+ self.assert_(a != b)
+ self.assert_(a <= b)
+ self.assert_(a < b)
+ self.assert_(a != "a.b.c.d")
+ self.assert_(a < "a.b.c.d")
+ self.assert_(a <= "a.b.c.d")
+ b = buffer("a.b")
+ self.assert_(a != b)
+ self.assert_(a >= b)
+ self.assert_(a > b)
+ self.assert_(a != "a.b")
+ self.assert_(a > "a.b")
+ self.assert_(a >= "a.b")
+ b = object()
+ self.assert_(a != b)
+ self.failIf(a == b)
+ self.assertRaises(TypeError, lambda: a < b)
+
+def test_main():
+ test_support.run_unittest(BufferTests)
+
+if __name__ == "__main__":
+ test_main()
diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py
index b0dbd4a..d3a272b 100644
--- a/Lib/test/test_builtin.py
+++ b/Lib/test/test_builtin.py
@@ -179,7 +179,8 @@ class BuiltinTest(unittest.TestCase):
self.assertRaises(ValueError, chr, 256)
self.assertRaises(TypeError, chr)
- def test_cmp(self):
+ def XXX_test_cmp(self):
+ # cmp() is no longer supported
self.assertEqual(cmp(-1, 1), -1)
self.assertEqual(cmp(1, -1), 1)
self.assertEqual(cmp(1, 1), 0)
@@ -1132,8 +1133,14 @@ class BuiltinTest(unittest.TestCase):
map(None, Squares(3), Squares(2)),
[(0,0), (1,1), (4,None)]
)
+ def Max(a, b):
+ if a is None:
+ return b
+ if b is None:
+ return a
+ return max(a, b)
self.assertEqual(
- map(max, Squares(3), Squares(2)),
+ map(Max, Squares(3), Squares(2)),
[0, 1, 4]
)
self.assertRaises(TypeError, map)
@@ -1201,7 +1208,7 @@ class BuiltinTest(unittest.TestCase):
class BadNumber:
def __cmp__(self, other):
raise ValueError
- self.assertRaises(ValueError, min, (42, BadNumber()))
+ self.assertRaises(TypeError, min, (42, BadNumber()))
for stmt in (
"min(key=int)", # no args
@@ -1379,8 +1386,11 @@ class BuiltinTest(unittest.TestCase):
self.assertRaises(ValueError, range, a, a + 1, long(0))
class badzero(int):
- def __cmp__(self, other):
+ def __eq__(self, other):
raise RuntimeError
+ __ne__ = __lt__ = __gt__ = __le__ = __ge__ = __eq__
+
+ # XXX This won't (but should!) raise RuntimeError if a is an int...
self.assertRaises(RuntimeError, range, a, a + 1, badzero(1))
# Reject floats when it would require PyLongs to represent.
@@ -1594,7 +1604,7 @@ class TestSorted(unittest.TestCase):
data.reverse()
random.shuffle(copy)
- self.assertEqual(data, sorted(copy, cmp=lambda x, y: cmp(y,x)))
+ self.assertEqual(data, sorted(copy, cmp=lambda x, y: (x < y) - (x > y)))
self.assertNotEqual(data, copy)
random.shuffle(copy)
self.assertEqual(data, sorted(copy, key=lambda x: -x))
diff --git a/Lib/test/test_calendar.py b/Lib/test/test_calendar.py
index e414324..893890d 100644
--- a/Lib/test/test_calendar.py
+++ b/Lib/test/test_calendar.py
@@ -212,7 +212,7 @@ class CalendarTestCase(unittest.TestCase):
self.assertEqual(calendar.isleap(2003), 0)
def test_setfirstweekday(self):
- self.assertRaises(ValueError, calendar.setfirstweekday, 'flabber')
+ self.assertRaises(TypeError, calendar.setfirstweekday, 'flabber')
self.assertRaises(ValueError, calendar.setfirstweekday, -1)
self.assertRaises(ValueError, calendar.setfirstweekday, 200)
orig = calendar.firstweekday()
diff --git a/Lib/test/test_cgi.py b/Lib/test/test_cgi.py
index 8fe487b..f93fa55 100644
--- a/Lib/test/test_cgi.py
+++ b/Lib/test/test_cgi.py
@@ -25,13 +25,11 @@ class ComparableException:
def __str__(self):
return str(self.err)
- def __cmp__(self, anExc):
+ def __eq__(self, anExc):
if not isinstance(anExc, Exception):
- return -1
- x = cmp(self.err.__class__, anExc.__class__)
- if x != 0:
- return x
- return cmp(self.err.args, anExc.args)
+ return NotImplemented
+ return (self.err.__class__ == anExc.__class__ and
+ self.err.args == anExc.args)
def __getattr__(self, attr):
return getattr(self.err, attr)
@@ -118,10 +116,10 @@ parse_strict_test_cases = [
})
]
-def norm(list):
- if type(list) == type([]):
- list.sort()
- return list
+def norm(seq):
+ if isinstance(seq, list):
+ seq.sort(key=repr)
+ return seq
def first_elts(list):
return map(lambda x:x[0], list)
diff --git a/Lib/test/test_class.py b/Lib/test/test_class.py
index a0b3300..66f4265 100644
--- a/Lib/test/test_class.py
+++ b/Lib/test/test_class.py
@@ -100,6 +100,30 @@ class AllTests:
print "__cmp__:", args
return 0
+ def __eq__(self, *args):
+ print "__eq__:", args
+ return True
+
+ def __ne__(self, *args):
+ print "__ne__:", args
+ return False
+
+ def __lt__(self, *args):
+ print "__lt__:", args
+ return False
+
+ def __le__(self, *args):
+ print "__le__:", args
+ return True
+
+ def __gt__(self, *args):
+ print "__gt__:", args
+ return False
+
+ def __ge__(self, *args):
+ print "__ge__:", args
+ return True
+
def __del__(self, *args):
print "__del__:", args
diff --git a/Lib/test/test_compare.py b/Lib/test/test_compare.py
index 7c81194..8f38e3b 100644
--- a/Lib/test/test_compare.py
+++ b/Lib/test/test_compare.py
@@ -13,8 +13,8 @@ class Cmp:
def __repr__(self):
return '<Cmp %s>' % self.arg
- def __cmp__(self, other):
- return cmp(self.arg, other)
+ def __eq__(self, other):
+ return self.arg == other
class ComparisonTest(unittest.TestCase):
set1 = [2, 2.0, 2L, 2+0j, Cmp(2.0)]
@@ -36,7 +36,7 @@ class ComparisonTest(unittest.TestCase):
L.insert(len(L)//2, Empty())
for a in L:
for b in L:
- self.assertEqual(cmp(a, b), cmp(id(a), id(b)),
+ self.assertEqual(a == b, id(a) == id(b),
'a=%r, b=%r' % (a, b))
def test_main():
diff --git a/Lib/test/test_copy.py b/Lib/test/test_copy.py
index ff4c987..416a755 100644
--- a/Lib/test/test_copy.py
+++ b/Lib/test/test_copy.py
@@ -104,8 +104,8 @@ class TestCopy(unittest.TestCase):
class C:
def __init__(self, foo):
self.foo = foo
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C(42)
self.assertEqual(copy.copy(x), x)
@@ -115,8 +115,8 @@ class TestCopy(unittest.TestCase):
self.foo = foo
def __copy__(self):
return C(self.foo)
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C(42)
self.assertEqual(copy.copy(x), x)
@@ -126,8 +126,8 @@ class TestCopy(unittest.TestCase):
self.foo = foo
def __getinitargs__(self):
return (self.foo,)
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C(42)
self.assertEqual(copy.copy(x), x)
@@ -137,8 +137,8 @@ class TestCopy(unittest.TestCase):
self.foo = foo
def __getstate__(self):
return {"foo": self.foo}
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C(42)
self.assertEqual(copy.copy(x), x)
@@ -148,8 +148,8 @@ class TestCopy(unittest.TestCase):
self.foo = foo
def __setstate__(self, state):
self.foo = state["foo"]
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C(42)
self.assertEqual(copy.copy(x), x)
@@ -161,8 +161,8 @@ class TestCopy(unittest.TestCase):
return self.foo
def __setstate__(self, state):
self.foo = state
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C(42)
self.assertEqual(copy.copy(x), x)
@@ -304,7 +304,7 @@ class TestCopy(unittest.TestCase):
x = {}
x['foo'] = x
y = copy.deepcopy(x)
- self.assertRaises(RuntimeError, cmp, y, x)
+ self.assertRaises(TypeError, cmp, y, x)
self.assert_(y is not x)
self.assert_(y['foo'] is y)
self.assertEqual(len(y), 1)
@@ -319,8 +319,8 @@ class TestCopy(unittest.TestCase):
class C:
def __init__(self, foo):
self.foo = foo
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
@@ -332,8 +332,8 @@ class TestCopy(unittest.TestCase):
self.foo = foo
def __deepcopy__(self, memo):
return C(copy.deepcopy(self.foo, memo))
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
@@ -346,8 +346,8 @@ class TestCopy(unittest.TestCase):
self.foo = foo
def __getinitargs__(self):
return (self.foo,)
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
@@ -360,8 +360,8 @@ class TestCopy(unittest.TestCase):
self.foo = foo
def __getstate__(self):
return {"foo": self.foo}
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
@@ -374,8 +374,8 @@ class TestCopy(unittest.TestCase):
self.foo = foo
def __setstate__(self, state):
self.foo = state["foo"]
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
@@ -390,8 +390,8 @@ class TestCopy(unittest.TestCase):
return self.foo
def __setstate__(self, state):
self.foo = state
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
@@ -434,8 +434,8 @@ class TestCopy(unittest.TestCase):
class C(object):
def __reduce__(self):
return (C, (), self.__dict__)
- def __cmp__(self, other):
- return cmp(self.__dict__, other.__dict__)
+ def __eq__(self, other):
+ return self.__dict__ == other.__dict__
x = C()
x.foo = [42]
y = copy.copy(x)
@@ -450,8 +450,8 @@ class TestCopy(unittest.TestCase):
return (C, (), self.__dict__)
def __setstate__(self, state):
self.__dict__.update(state)
- def __cmp__(self, other):
- return cmp(self.__dict__, other.__dict__)
+ def __eq__(self, other):
+ return self.__dict__ == other.__dict__
x = C()
x.foo = [42]
y = copy.copy(x)
@@ -475,9 +475,9 @@ class TestCopy(unittest.TestCase):
class C(list):
def __reduce__(self):
return (C, (), self.__dict__, iter(self))
- def __cmp__(self, other):
- return (cmp(list(self), list(other)) or
- cmp(self.__dict__, other.__dict__))
+ def __eq__(self, other):
+ return (list(self) == list(other) and
+ self.__dict__ == other.__dict__)
x = C([[1, 2], 3])
y = copy.copy(x)
self.assertEqual(x, y)
@@ -492,9 +492,9 @@ class TestCopy(unittest.TestCase):
class C(dict):
def __reduce__(self):
return (C, (), self.__dict__, None, self.iteritems())
- def __cmp__(self, other):
- return (cmp(dict(self), list(dict)) or
- cmp(self.__dict__, other.__dict__))
+ def __eq__(self, other):
+ return (dict(self) == dict(other) and
+ self.__dict__ == other.__dict__)
x = C([("foo", [1, 2]), ("bar", 3)])
y = copy.copy(x)
self.assertEqual(x, y)
diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py
index 40c4466..5fef4eb 100644
--- a/Lib/test/test_decimal.py
+++ b/Lib/test/test_decimal.py
@@ -276,8 +276,8 @@ class DecimalTest(unittest.TestCase):
myexceptions = self.getexceptions()
self.context.clear_flags()
- myexceptions.sort()
- theirexceptions.sort()
+ myexceptions.sort(key=repr)
+ theirexceptions.sort(key=repr)
self.assertEqual(result, ans,
'Incorrect answer for ' + s + ' -- got ' + result)
diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py
index 00800a7..3fb01e7 100644
--- a/Lib/test/test_descr.py
+++ b/Lib/test/test_descr.py
@@ -151,7 +151,7 @@ def lists():
def dicts():
if verbose: print "Testing dict operations..."
- testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
+ ##testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
@@ -523,7 +523,7 @@ def spamdicts():
# This is an ugly hack:
copy._deepcopy_dispatch[spam.spamdict] = spamdict
- testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
+ ##testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
@@ -1641,7 +1641,7 @@ def specials():
verify(id(c1) != id(c2))
hash(c1)
hash(c2)
- vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
+ ##vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
vereq(c1, c1)
verify(c1 != c2)
verify(not c1 != c1)
@@ -1665,7 +1665,7 @@ def specials():
verify(id(d1) != id(d2))
hash(d1)
hash(d2)
- vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
+ ##vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
vereq(d1, d1)
verify(d1 != d2)
verify(not d1 != d1)
@@ -1758,21 +1758,21 @@ def specials():
for i in range(10):
verify(i in p10)
verify(10 not in p10)
- # Safety test for __cmp__
- def unsafecmp(a, b):
- try:
- a.__class__.__cmp__(a, b)
- except TypeError:
- pass
- else:
- raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
- a.__class__, a, b)
- unsafecmp(u"123", "123")
- unsafecmp("123", u"123")
- unsafecmp(1, 1.0)
- unsafecmp(1.0, 1)
- unsafecmp(1, 1L)
- unsafecmp(1L, 1)
+## # Safety test for __cmp__
+## def unsafecmp(a, b):
+## try:
+## a.__class__.__cmp__(a, b)
+## except TypeError:
+## pass
+## else:
+## raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
+## a.__class__, a, b)
+## unsafecmp(u"123", "123")
+## unsafecmp("123", u"123")
+## unsafecmp(1, 1.0)
+## unsafecmp(1.0, 1)
+## unsafecmp(1, 1L)
+## unsafecmp(1L, 1)
class Letter(str):
def __new__(cls, letter):
@@ -2469,12 +2469,43 @@ def classic_comparisons():
class C(base):
def __init__(self, value):
self.value = int(value)
- def __cmp__(self, other):
+ def __eq__(self, other):
+ if isinstance(other, C):
+ return self.value == other.value
+ if isinstance(other, int) or isinstance(other, long):
+ return self.value == other
+ return NotImplemented
+ def __ne__(self, other):
+ if isinstance(other, C):
+ return self.value != other.value
+ if isinstance(other, int) or isinstance(other, long):
+ return self.value != other
+ return NotImplemented
+ def __lt__(self, other):
+ if isinstance(other, C):
+ return self.value < other.value
+ if isinstance(other, int) or isinstance(other, long):
+ return self.value < other
+ return NotImplemented
+ def __le__(self, other):
+ if isinstance(other, C):
+ return self.value <= other.value
+ if isinstance(other, int) or isinstance(other, long):
+ return self.value <= other
+ return NotImplemented
+ def __gt__(self, other):
if isinstance(other, C):
- return cmp(self.value, other.value)
+ return self.value > other.value
+ if isinstance(other, int) or isinstance(other, long):
+ return self.value > other
+ return NotImplemented
+ def __ge__(self, other):
+ if isinstance(other, C):
+ return self.value >= other.value
if isinstance(other, int) or isinstance(other, long):
- return cmp(self.value, other)
+ return self.value >= other
return NotImplemented
+
c1 = C(1)
c2 = C(2)
c3 = C(3)
@@ -2482,12 +2513,12 @@ def classic_comparisons():
c = {1: c1, 2: c2, 3: c3}
for x in 1, 2, 3:
for y in 1, 2, 3:
- verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
+ ##verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
for op in "<", "<=", "==", "!=", ">", ">=":
verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
"x=%d, y=%d" % (x, y))
- verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
- verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
+ ##verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
+ ##verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
def rich_comparisons():
if verbose:
@@ -3875,6 +3906,8 @@ def methodwrapper():
if verbose:
print "Testing method-wrapper objects..."
+ return # XXX should methods really support __eq__?
+
l = []
vereq(l.__add__, l.__add__)
vereq(l.__add__, [].__add__)
diff --git a/Lib/test/test_descrtut.py b/Lib/test/test_descrtut.py
index 6a5310c..28d7d13 100644
--- a/Lib/test/test_descrtut.py
+++ b/Lib/test/test_descrtut.py
@@ -65,14 +65,11 @@ We can also use the new type in contexts where classic only allows "real"
dictionaries, such as the locals/globals dictionaries for the exec
statement or the built-in function eval():
- >>> def sorted(seq):
- ... seq.sort()
- ... return seq
>>> print sorted(a.keys())
[1, 2]
>>> exec "x = 3; print x" in a
3
- >>> print sorted(a.keys())
+ >>> print sorted(a.keys(), key=lambda x: (str(type(x)), x))
[1, 2, '__builtins__', 'x']
>>> print a['x']
3
diff --git a/Lib/test/test_dict.py b/Lib/test/test_dict.py
index 7295f41..717ed5e 100644
--- a/Lib/test/test_dict.py
+++ b/Lib/test/test_dict.py
@@ -5,6 +5,7 @@ import sys, UserDict, cStringIO
class DictTest(unittest.TestCase):
+
def test_constructor(self):
# calling built-in types without argument must return empty
self.assertEqual(dict(), {})
@@ -368,9 +369,9 @@ class DictTest(unittest.TestCase):
d = {1: BadRepr()}
self.assertRaises(Exc, repr, d)
- def test_le(self):
- self.assert_(not ({} < {}))
- self.assert_(not ({1: 2} < {1L: 2L}))
+ def test_eq(self):
+ self.assertEqual({}, {})
+ self.assertEqual({1: 2}, {1L: 2L})
class Exc(Exception): pass
@@ -378,12 +379,12 @@ class DictTest(unittest.TestCase):
def __eq__(self, other):
raise Exc()
def __hash__(self):
- return 42
+ return 1
d1 = {BadCmp(): 1}
d2 = {1: 1}
try:
- d1 < d2
+ d1 == d2
except Exc:
pass
else:
diff --git a/Lib/test/test_grammar.py b/Lib/test/test_grammar.py
index 296dc9b..458bfa2 100644
--- a/Lib/test/test_grammar.py
+++ b/Lib/test/test_grammar.py
@@ -681,7 +681,7 @@ d[1,] = 2
d[1,2] = 3
d[1,2,3] = 4
L = list(d)
-L.sort()
+L.sort(key=lambda x: x if isinstance(x, tuple) else ())
print L
@@ -741,7 +741,7 @@ print [(i, s) for i in nums for s in [f for f in strs if "n" in f]]
print [(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)]
def test_in_func(l):
- return [None < x < 3 for x in l if x > 2]
+ return [0 < x < 3 for x in l if x > 2]
print test_in_func(nums)
diff --git a/Lib/test/test_heapq.py b/Lib/test/test_heapq.py
index 2da4f8c..1916449 100644
--- a/Lib/test/test_heapq.py
+++ b/Lib/test/test_heapq.py
@@ -136,6 +136,7 @@ class CmpErr:
"Dummy element that always raises an error during comparison"
def __cmp__(self, other):
raise ZeroDivisionError
+ __eq__ = __ne__ = __lt__ = __le__ = __gt__ = __ge__ = __cmp__
def R(seqn):
'Regular generator'
@@ -253,7 +254,7 @@ class TestErrorHandling(unittest.TestCase):
def test_iterable_args(self):
for f in (nlargest, nsmallest):
- for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
+ for s in ("123", "", range(1000), (1, 1.2), xrange(2000,2200,5)):
for g in (G, I, Ig, L, R):
self.assertEqual(f(2, g(s)), f(2,s))
self.assertEqual(f(2, S(s)), [])
diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
index b2a9b55..29abd4b 100644
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -132,13 +132,13 @@ class TestBasicOps(unittest.TestCase):
# __cmp__ failure
class DummyCmp:
- def __cmp__(self, dst):
+ def __eq__(self, dst):
raise ExpectedError
s = [DummyCmp(), DummyCmp(), None]
- # __cmp__ failure on outer object
+ # __eq__ failure on outer object
self.assertRaises(ExpectedError, gulp, s, func=id)
- # __cmp__ failure on inner object
+ # __eq__ failure on inner object
self.assertRaises(ExpectedError, gulp, s)
# keyfunc failure
diff --git a/Lib/test/test_mutants.py b/Lib/test/test_mutants.py
index df58944..39ea806 100644
--- a/Lib/test/test_mutants.py
+++ b/Lib/test/test_mutants.py
@@ -27,7 +27,7 @@ import os
# ran it. Indeed, at the start, the driver never got beyond 6 iterations
# before the test died.
-# The dicts are global to make it easy to mutate tham from within functions.
+# The dicts are global to make it easy to mutate them from within functions.
dict1 = {}
dict2 = {}
@@ -93,9 +93,9 @@ class Horrid:
def __hash__(self):
return self.hashcode
- def __cmp__(self, other):
+ def __eq__(self, other):
maybe_mutate() # The point of the test.
- return cmp(self.i, other.i)
+ return self.i == other.i
def __repr__(self):
return "Horrid(%d)" % self.i
@@ -132,7 +132,8 @@ def test_one(n):
while dict1 and len(dict1) == len(dict2):
if verbose:
print ".",
- c = cmp(dict1, dict2)
+ c = dict1 == dict2
+ XXX # Can't figure out how to make this work
if verbose:
print
diff --git a/Lib/test/test_operations.py b/Lib/test/test_operations.py
index 0b558de..67e77aa 100644
--- a/Lib/test/test_operations.py
+++ b/Lib/test/test_operations.py
@@ -12,7 +12,7 @@ class BadDictKey:
def __hash__(self):
return hash(self.__class__)
- def __cmp__(self, other):
+ def __eq__(self, other):
if isinstance(other, self.__class__):
print "raising error"
raise RuntimeError, "gotcha"
@@ -34,7 +34,7 @@ for stmt in ['d[x2] = 2',
except RuntimeError:
print "%s: caught the RuntimeError outside" % (stmt,)
else:
- print "%s: No exception passed through!" # old CPython behavior
+ print "%s: No exception passed through!" % (stmt,) # old CPython behavior
# Dict resizing bug, found by Jack Jansen in 2.2 CVS development.
diff --git a/Lib/test/test_set.py b/Lib/test/test_set.py
index 0268be2..23926be 100644
--- a/Lib/test/test_set.py
+++ b/Lib/test/test_set.py
@@ -18,7 +18,7 @@ def check_pass_thru():
class BadCmp:
def __hash__(self):
return 1
- def __cmp__(self, other):
+ def __eq__(self, other):
raise RuntimeError
class TestJointOps(unittest.TestCase):
@@ -781,11 +781,8 @@ class TestBinaryOps(unittest.TestCase):
a, b = set('a'), set('b')
self.assertRaises(TypeError, cmp, a, b)
- # You can view this as a buglet: cmp(a, a) does not raise TypeError,
- # because __eq__ is tried before __cmp__, and a.__eq__(a) returns True,
- # which Python thinks is good enough to synthesize a cmp() result
- # without calling __cmp__.
- self.assertEqual(cmp(a, a), 0)
+ # In py3k, this works!
+ self.assertRaises(TypeError, cmp, a, a)
self.assertRaises(TypeError, cmp, a, 12)
self.assertRaises(TypeError, cmp, "abc", a)
@@ -1201,8 +1198,8 @@ class TestCopying(unittest.TestCase):
def test_copy(self):
dup = self.set.copy()
- dup_list = list(dup); dup_list.sort()
- set_list = list(self.set); set_list.sort()
+ dup_list = sorted(dup, key=repr)
+ set_list = sorted(self.set, key=repr)
self.assertEqual(len(dup_list), len(set_list))
for i in range(len(dup_list)):
self.failUnless(dup_list[i] is set_list[i])
@@ -1210,8 +1207,8 @@ class TestCopying(unittest.TestCase):
def test_deep_copy(self):
dup = copy.deepcopy(self.set)
##print type(dup), repr(dup)
- dup_list = list(dup); dup_list.sort()
- set_list = list(self.set); set_list.sort()
+ dup_list = sorted(dup, key=repr)
+ set_list = sorted(self.set, key=repr)
self.assertEqual(len(dup_list), len(set_list))
for i in range(len(dup_list)):
self.assertEqual(dup_list[i], set_list[i])
@@ -1374,7 +1371,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
for cons in (set, frozenset):
for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
- self.assertEqual(sorted(cons(g(s))), sorted(g(s)))
+ self.assertEqual(sorted(cons(g(s)), key=repr), sorted(g(s), key=repr))
self.assertRaises(TypeError, cons , X(s))
self.assertRaises(TypeError, cons , N(s))
self.assertRaises(ZeroDivisionError, cons , E(s))
@@ -1386,7 +1383,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
for g in (G, I, Ig, L, R):
expected = meth(data)
actual = meth(G(data))
- self.assertEqual(sorted(actual), sorted(expected))
+ self.assertEqual(sorted(actual, key=repr), sorted(expected, key=repr))
self.assertRaises(TypeError, meth, X(s))
self.assertRaises(TypeError, meth, N(s))
self.assertRaises(ZeroDivisionError, meth, E(s))
@@ -1400,7 +1397,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
t = s.copy()
getattr(s, methname)(list(g(data)))
getattr(t, methname)(g(data))
- self.assertEqual(sorted(s), sorted(t))
+ self.assertEqual(sorted(s, key=repr), sorted(t, key=repr))
self.assertRaises(TypeError, getattr(set('january'), methname), X(data))
self.assertRaises(TypeError, getattr(set('january'), methname), N(data))
diff --git a/Lib/test/test_sets.py b/Lib/test/test_sets.py
index 85e4a22..88cfcac 100644
--- a/Lib/test/test_sets.py
+++ b/Lib/test/test_sets.py
@@ -234,11 +234,8 @@ class TestBinaryOps(unittest.TestCase):
a, b = Set('a'), Set('b')
self.assertRaises(TypeError, cmp, a, b)
- # You can view this as a buglet: cmp(a, a) does not raise TypeError,
- # because __eq__ is tried before __cmp__, and a.__eq__(a) returns True,
- # which Python thinks is good enough to synthesize a cmp() result
- # without calling __cmp__.
- self.assertEqual(cmp(a, a), 0)
+ # In py3k, this works!
+ self.assertRaises(TypeError, cmp, a, a)
self.assertRaises(TypeError, cmp, a, 12)
self.assertRaises(TypeError, cmp, "abc", a)
@@ -675,8 +672,8 @@ class TestCopying(unittest.TestCase):
def test_copy(self):
dup = self.set.copy()
- dup_list = list(dup); dup_list.sort()
- set_list = list(self.set); set_list.sort()
+ dup_list = sorted(dup, key=repr)
+ set_list = sorted(self.set, key=repr)
self.assertEqual(len(dup_list), len(set_list))
for i in range(len(dup_list)):
self.failUnless(dup_list[i] is set_list[i])
@@ -684,8 +681,8 @@ class TestCopying(unittest.TestCase):
def test_deep_copy(self):
dup = copy.deepcopy(self.set)
##print type(dup), repr(dup)
- dup_list = list(dup); dup_list.sort()
- set_list = list(self.set); set_list.sort()
+ dup_list = sorted(dup, key=repr)
+ set_list = sorted(self.set, key=repr)
self.assertEqual(len(dup_list), len(set_list))
for i in range(len(dup_list)):
self.assertEqual(dup_list[i], set_list[i])
diff --git a/Lib/test/test_slice.py b/Lib/test/test_slice.py
index d8eb882..bd6e621 100644
--- a/Lib/test/test_slice.py
+++ b/Lib/test/test_slice.py
@@ -35,18 +35,18 @@ class SliceTest(unittest.TestCase):
s1 = slice(BadCmp())
s2 = slice(BadCmp())
- self.assertRaises(Exc, cmp, s1, s2)
self.assertEqual(s1, s1)
+ self.assertRaises(Exc, lambda: s1 == s2)
s1 = slice(1, BadCmp())
s2 = slice(1, BadCmp())
self.assertEqual(s1, s1)
- self.assertRaises(Exc, cmp, s1, s2)
+ self.assertRaises(Exc, lambda: s1 == s2)
s1 = slice(1, 2, BadCmp())
s2 = slice(1, 2, BadCmp())
self.assertEqual(s1, s1)
- self.assertRaises(Exc, cmp, s1, s2)
+ self.assertRaises(Exc, lambda: s1 == s2)
def test_members(self):
s = slice(1)
diff --git a/Lib/test/test_sort.py b/Lib/test/test_sort.py
index 84c92cc..031780a 100644
--- a/Lib/test/test_sort.py
+++ b/Lib/test/test_sort.py
@@ -68,8 +68,8 @@ class TestBase(unittest.TestCase):
self.key = key
self.index = i
- def __cmp__(self, other):
- return cmp(self.key, other.key)
+ def __lt__(self, other):
+ return self.key < other.key
def __repr__(self):
return "Stable(%d, %d)" % (self.key, self.index)
@@ -225,6 +225,8 @@ class TestDecorateSortUndecorate(unittest.TestCase):
def __del__(self):
del data[:]
data[:] = range(20)
+ def __lt__(self, other):
+ return id(self) < id(other)
self.assertRaises(ValueError, data.sort, key=SortKiller)
def test_key_with_mutating_del_and_exception(self):
diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py
index 0397118..d260fc5 100644
--- a/Lib/test/test_support.py
+++ b/Lib/test/test_support.py
@@ -122,8 +122,8 @@ def fcmp(x, y): # fuzzy comparison function
outcome = fcmp(x[i], y[i])
if outcome != 0:
return outcome
- return cmp(len(x), len(y))
- return cmp(x, y)
+ return (len(x) > len(y)) - (len(x) < len(y))
+ return (x > y) - (x < y)
try:
unicode
diff --git a/Lib/test/test_types.py b/Lib/test/test_types.py
index 2d299c3..f0bdfde 100644
--- a/Lib/test/test_types.py
+++ b/Lib/test/test_types.py
@@ -233,7 +233,6 @@ print 'Buffers'
try: buffer('asdf', -1)
except ValueError: pass
else: raise TestFailed, "buffer('asdf', -1) should raise ValueError"
-cmp(buffer("abc"), buffer("def")) # used to raise a warning: tp_compare didn't return -1, 0, or 1
try: buffer(None)
except TypeError: pass
diff --git a/Lib/test/test_userdict.py b/Lib/test/test_userdict.py
index ecb33d1..bc45bf3 100644
--- a/Lib/test/test_userdict.py
+++ b/Lib/test/test_userdict.py
@@ -52,7 +52,7 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol):
all = [d0, d1, d2, u, u0, u1, u2, uu, uu0, uu1, uu2]
for a in all:
for b in all:
- self.assertEqual(cmp(a, b), cmp(len(a), len(b)))
+ self.assertEqual(a == b, len(a) == len(b))
# Test __getitem__
self.assertEqual(u2["one"], 1)
diff --git a/Lib/test/test_weakref.py b/Lib/test/test_weakref.py
index a4fb7f3..f5114b2 100644
--- a/Lib/test/test_weakref.py
+++ b/Lib/test/test_weakref.py
@@ -701,6 +701,12 @@ class Object:
self.arg = arg
def __repr__(self):
return "<Object %r>" % self.arg
+ def __lt__(self, other):
+ if isinstance(other, Object):
+ return self.arg < other.arg
+ return NotImplemented
+ def __hash__(self):
+ return hash(self.arg)
class MappingTestCase(TestBase):
diff --git a/Lib/uuid.py b/Lib/uuid.py
index ae3da25..5bf5c35 100644
--- a/Lib/uuid.py
+++ b/Lib/uuid.py
@@ -177,9 +177,36 @@ class UUID(object):
int |= version << 76L
self.__dict__['int'] = int
- def __cmp__(self, other):
+ def __eq__(self, other):
if isinstance(other, UUID):
- return cmp(self.int, other.int)
+ return self.int == other.int
+ return NotImplemented
+
+ def __ne__(self, other):
+ if isinstance(other, UUID):
+ return self.int != other.int
+ return NotImplemented
+
+ # XXX What's the value of being able to sort UUIDs?
+
+ def __lt__(self, other):
+ if isinstance(other, UUID):
+ return self.int < other.int
+ return NotImplemented
+
+ def __gt__(self, other):
+ if isinstance(other, UUID):
+ return self.int > other.int
+ return NotImplemented
+
+ def __le__(self, other):
+ if isinstance(other, UUID):
+ return self.int <= other.int
+ return NotImplemented
+
+ def __ge__(self, other):
+ if isinstance(other, UUID):
+ return self.int >= other.int
return NotImplemented
def __hash__(self):
@@ -488,7 +515,7 @@ def uuid1(node=None, clock_seq=None):
# 0x01b21dd213814000 is the number of 100-ns intervals between the
# UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
timestamp = int(nanoseconds/100) + 0x01b21dd213814000L
- if timestamp <= _last_timestamp:
+ if _last_timestamp is not None and timestamp <= _last_timestamp:
timestamp = _last_timestamp + 1
_last_timestamp = timestamp
if clock_seq is None:
diff --git a/Lib/xmlrpclib.py b/Lib/xmlrpclib.py
index d1bd2d8..72866f1 100644
--- a/Lib/xmlrpclib.py
+++ b/Lib/xmlrpclib.py
@@ -282,56 +282,9 @@ class Fault(Error):
# @param value A boolean value. Any true value is interpreted as True,
# all other values are interpreted as False.
-if _bool_is_builtin:
- boolean = Boolean = bool
- # to avoid breaking code which references xmlrpclib.{True,False}
- True, False = True, False
-else:
- class Boolean:
- """Boolean-value wrapper.
-
- Use True or False to generate a "boolean" XML-RPC value.
- """
-
- def __init__(self, value = 0):
- self.value = operator.truth(value)
-
- def encode(self, out):
- out.write("<value><boolean>%d</boolean></value>\n" % self.value)
-
- def __cmp__(self, other):
- if isinstance(other, Boolean):
- other = other.value
- return cmp(self.value, other)
-
- def __repr__(self):
- if self.value:
- return "<Boolean True at %x>" % id(self)
- else:
- return "<Boolean False at %x>" % id(self)
-
- def __int__(self):
- return self.value
-
- def __nonzero__(self):
- return self.value
-
- True, False = Boolean(1), Boolean(0)
-
- ##
- # Map true or false value to XML-RPC boolean values.
- #
- # @def boolean(value)
- # @param value A boolean value. Any true value is mapped to True,
- # all other values are mapped to False.
- # @return xmlrpclib.True or xmlrpclib.False.
- # @see Boolean
- # @see True
- # @see False
-
- def boolean(value, _truefalse=(False, True)):
- """Convert any Python value to XML-RPC 'boolean'."""
- return _truefalse[operator.truth(value)]
+boolean = Boolean = bool
+# to avoid breaking code which references xmlrpclib.{True,False}
+True, False = True, False
##
# Wrapper for XML-RPC DateTime values. This converts a time value to
@@ -371,10 +324,15 @@ class DateTime:
value = time.strftime("%Y%m%dT%H:%M:%S", value)
self.value = value
- def __cmp__(self, other):
+ def __eq__(self, other):
if isinstance(other, DateTime):
other = other.value
- return cmp(self.value, other)
+ return self.value == other
+
+ def __ne__(self, other):
+ if isinstance(other, DateTime):
+ other = other.value
+ return self.value != other
##
# Get date/time value.
@@ -432,10 +390,15 @@ class Binary:
def __str__(self):
return self.data or ""
- def __cmp__(self, other):
+ def __eq__(self, other):
+ if isinstance(other, Binary):
+ other = other.data
+ return self.data == other
+
+ def __ne__(self, other):
if isinstance(other, Binary):
other = other.data
- return cmp(self.data, other)
+ return self.data != other
def decode(self, data):
self.data = base64.decodestring(data)