我们从Python开源项目中,提取了以下6个代码示例,用于说明如何使用past.builtins.cmp()。
def test_cmp(self): self.assertEqual(cmp(-1, 1), -1) self.assertEqual(cmp(1, -1), 1) self.assertEqual(cmp(1, 1), 0) # verify that circular objects are not handled a = []; a.append(a) b = []; b.append(b) from UserList import UserList c = UserList(); c.append(c) self.assertRaises(RuntimeError, cmp, a, b) self.assertRaises(RuntimeError, cmp, b, c) self.assertRaises(RuntimeError, cmp, c, a) self.assertRaises(RuntimeError, cmp, a, c) # okay, now break the cycles a.pop(); b.pop(); c.pop() self.assertRaises(TypeError, cmp)
def test_basic(self): data = range(100) copy = data[:] random.shuffle(copy) self.assertEqual(data, sorted(copy)) self.assertNotEqual(data, copy) data.reverse() random.shuffle(copy) self.assertEqual(data, sorted(copy, cmp=lambda x, y: cmp(y,x))) self.assertNotEqual(data, copy) random.shuffle(copy) self.assertEqual(data, sorted(copy, key=lambda x: -x)) self.assertNotEqual(data, copy) random.shuffle(copy) self.assertEqual(data, sorted(copy, reverse=1)) self.assertNotEqual(data, copy)
def test_cmp(self): before = """ assert cmp(1, 2) == -1 assert cmp(2, 1) == 1 """ after = """ from past.builtins import cmp assert cmp(1, 2) == -1 assert cmp(2, 1) == 1 """ self.convert_check(before, after, stages=(1, 2), ignore_imports=False)
def __cmp__(self, y): """Compare two duration objects""" if isinstance(y, duration): return cmp(self.value, y.value) elif isinstance(y, (int, float)): return cmp(self.value, y) else: raise DurationComparisonError
def __cmp__(self, y): """Compare two timestamps""" if isinstance(y, timestamp): return cmp(self.value, y.value) else: raise TimestampComparisonError
def base_cmp(cls, a, b): x = cmp(a.start, b.start) return x if x != 0 else -cmp(a.end, b.end)